问:
Warnings while building Rakudo in Windows
I followed the instructions for building Rakudo here. With similar reading here and here, I tried building it in Windows with VS-2019.

However, while building Rakudo in windows I get the following build warnings:

```<code>Updating submodules .................................... OK
Configuring native build environment ...................
    trying to compile a simple C program ............... YES
did not find libzstd; will not use heap snapshot format version 3
OK
...
src\io\syncfile.c(272): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
src\io\syncfile.c(334): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
...
src\io\signals.c(115): warning C4068: unknown pragma
src\io\signals.c(116): warning C4068: unknown pragma
src\io\signals.c(120): warning C4068: unknown pragma
...
src\platform\random.c(132): warning C4113: 'FARPROC' differs in parameter lists from 'CRYPTGENRANDOM'
src\platform\random.c(132): warning C4133: '=': incompatible types - from 'FARPROC' to 'CRYPTGENRANDOM'
src\platform\random.c(130): warning C4113: 'FARPROC' differs in parameter lists from 'CRYPTACQUIRECONTEXTA'
src\platform\random.c(130): warning C4133: 'initializing': incompatible types - from 'FARPROC' to 'CRYPTACQUIRECONTEXTA'
...
src\platform\win32\io.c(27): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
src\platform\win32\io.c(116): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
...
cl : Command line warning D9035 : option 'o' has been deprecated and will be removed in a future release
cl : Command line warning D9002 : ignoring unknown option '-lm'
minilua.c
...
src\jit\x64\emit.c(8): warning C4129: 'j': unrecognized character escape sequence
src\jit\x64\emit.c(8): warning C4129: 'e': unrecognized character escape sequence
srcjitdemit.dasc(4): warning C4068: unknown pragma
srcjitdemit.dasc(5): warning C4068: unknown pragma
srcjitdemit.dasc(7): warning C4068: unknown pragma
srcjitdemit.dasc(8): warning C4068: unknown pragma
src/jit/x64/tiles.dasc(2): warning C4068: unknown pragma
...
</code>```

Only the warnings are shown in the above code block. The full log is given here.

System used for build: Appveyor with VS-2019 in Windows

Configuration:

```<code>## Appveyor configuration for Rakudo

# Manually build and don't use MSVC's build process so disable it
build: off

platform:
  - x64

install:
  - '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"'
  # install zstd
  - choco install zstandard
  - SET PATH=C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;%PATH%
  - perl Configure.pl --gen-moar --gen-nqp --backends=moar --prefix=%APPVEYOR_BUILD_FOLDER%\raku
  - nmake
  - nmake install

environment:
  matrix:
  - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019

branches:
  only:
    - master
</code>```

Though I have installed zstandard(https://github.com/facebook/zstd) from chocolatey, why do I get .. did not find libzstd; will not use heap snapshot format version 3

Are these warnings (other than zstd) during the build innocuous which I can ignore safely? Or I should worry about?

Is there a way to get rid of these warnings?

答:
I took a quick look:

The warning about conversion from 'int' to 'HANDLE' of greater size are probably due to a missing #include <io.h>, which leads to the compiler assuming that _get_osfhandle() returns int instead of intptr_t. This is potentially a bug (though it might not manifest in practice depending on the range of values windows actually returns from that function).

The warnings about 'FARPROC' differs in parameter lists are due to missing casts from the generic pointer returned by GetProcAddress() to the specific type. However, because all pointer types have compatible representation, nothing bad can happen if ignored.

The warnings about the pragmas can be ignored as well, and could be suppressed with a judicious use of #ifdef __GNUC__.

The warnings about unrecognized character escape sequence are due to not properly escaping backslashes in paths in generated code. Should be fixed, but can be ignored as well.

Regarding zstd, the configuration script uses pkg-config to find the library, so no windows support. Someone should fix that. However, I believe this will only affect the profiler, not regular operation of MoarVM.

I did not investigate the Command line warning stuff, though it looks like something thinks it's compiling on a *nix system and hence passes incorrect flags. Should be fixed, but might not break the build.

Body:
I followed the instructions for building Rakudo here. With similar reading here and here, I tried building it in Windows with VS-2019.

However, while building Rakudo in windows I get the following build warnings:

Updating submodules .................................... OK
Configuring native build environment ...................
    trying to compile a simple C program ............... YES
did not find libzstd; will not use heap snapshot format version 3
OK
...
src\io\syncfile.c(272): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
src\io\syncfile.c(334): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
...
src\io\signals.c(115): warning C4068: unknown pragma
src\io\signals.c(116): warning C4068: unknown pragma
src\io\signals.c(120): warning C4068: unknown pragma
...
src\platform\random.c(132): warning C4113: 'FARPROC' differs in parameter lists from 'CRYPTGENRANDOM'
src\platform\random.c(132): warning C4133: '=': incompatible types - from 'FARPROC' to 'CRYPTGENRANDOM'
src\platform\random.c(130): warning C4113: 'FARPROC' differs in parameter lists from 'CRYPTACQUIRECONTEXTA'
src\platform\random.c(130): warning C4133: 'initializing': incompatible types - from 'FARPROC' to 'CRYPTACQUIRECONTEXTA'
...
src\platform\win32\io.c(27): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
src\platform\win32\io.c(116): warning C4312: 'type cast': conversion from 'int' to 'HANDLE' of greater size
...
cl : Command line warning D9035 : option 'o' has been deprecated and will be removed in a future release
cl : Command line warning D9002 : ignoring unknown option '-lm'
minilua.c
...
src\jit\x64\emit.c(8): warning C4129: 'j': unrecognized character escape sequence
src\jit\x64\emit.c(8): warning C4129: 'e': unrecognized character escape sequence
srcjitdemit.dasc(4): warning C4068: unknown pragma
srcjitdemit.dasc(5): warning C4068: unknown pragma
srcjitdemit.dasc(7): warning C4068: unknown pragma
srcjitdemit.dasc(8): warning C4068: unknown pragma
src/jit/x64/tiles.dasc(2): warning C4068: unknown pragma
...

Only the warnings are shown in the above code block. The full log is given here.

System used for build: Appveyor with VS-2019 in Windows

Configuration:

## Appveyor configuration for Rakudo

# Manually build and don't use MSVC's build process so disable it
build: off

platform:
  - x64

install:
  - '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"'
  # install zstd
  - choco install zstandard
  - SET PATH=C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;%PATH%
  - perl Configure.pl --gen-moar --gen-nqp --backends=moar --prefix=%APPVEYOR_BUILD_FOLDER%\raku
  - nmake
  - nmake install

environment:
  matrix:
  - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019

branches:
  only:
    - master

Though I have installed zstandard(https://github.com/facebook/zstd) from chocolatey, why do I get .. did not find libzstd; will not use heap snapshot format version 3

Are these warnings (other than zstd) during the build innocuous which I can ignore safely? Or I should worry about?

Is there a way to get rid of these warnings?


来源: stackexchange

问:
I want to call blazor component dynamically on button click
I have TemplateSlide.razor component like below

```<code><div class="slide-panel">
  <div class="contact-form-content">
          @Content

 </div>
@code
{
[Parameter] public RenderFragment Content { get; set; }
}
</code>```

I have razor component Comp.razor like following

```<code><TemplateSlide>
<div>Other comp</div>
</TemplateSlide>
</code>```

I have other menu component that call Comp.razor on button click

```<code> <div class="page-header-buttons">
        <ul>

            <li class="page-header-buttons-items can-add">
                <MainMenuLink Href="" ActiveClass="page-header-active" HrefMatch="MainMenuLinkMatch.Exact">
                    Dashboard
                </MainMenuLink>

                @*<a class="page-header-plus contact" href="#"><i class="fas fa-plus add-new-contact-icon"></i></a>*@
            </li>
            <li class="page-header-buttons-items can-add">
                <MainMenuLink Href="contacts" ActiveClass="page-header-active">
                    Contacts
                </MainMenuLink>
                <a class="page-header-plus contact"   @onclick="@(()=>Show<Comp>())"><i class="fas fa-plus add-new-contact-icon"></i></a>

            </li>
<li class="page-header-buttons-items can-add">
                <MainMenuLink Href="contacts" ActiveClass="page-header-active">
                    Others
                </MainMenuLink>
                <a class="page-header-plus contact"   @onclick="@(()=>Show<Others>())"><i class="fas fa-plus add-new-contact-icon"></i></a>

            </li>
</ul>
    </div>
</code>```

How can write generic and dynamic Show method for button click?

答:
I learned this yesterday and I am only posting this in case it helps someone.

I have a list of users I display in my Blazor Chat, and the names are actually buttons:

```<code>@foreach (SubscriberCallback callback in Names)
{
    <button class="listbutton" @onclick="(Action<EventArgs>) (args =>
    SendPrivateMessageClicked(args, callback.Id))">@callback.Name</button><br />
}
</code>```

I have this method called SendPrivateMessageClicked, and I need to pass in the Id (Guid) of who to send the message to.

```<code>private void SendPrivateMessageClicked(EventArgs args, Guid toId)
{
    // Attempt to find the subscriber
    SubscriberCallback subscriber = SubscriberService.FindSubscriber(toId);

    // Send Private Message Code Removed, but you get the point
}
</code>```

Css for the link button:

```<code>.listbutton
{
    background:none;
    border:none;
    margin:0;
    padding:0;
    cursor: pointer;
    border: none;
    color: limegreen;
    height: 2.4vh;
    font-size: 2vh;
}
.listbutton:focus
{
    outline: none;
}
</code>```

I love Blazor!

ContentLicense: CC BY-SA 4.0

Body:
I have TemplateSlide.razor component like below

          @Content

@code
{
[Parameter] public RenderFragment Content { get; set; }
}

I have razor component Comp.razor like following

<TemplateSlide>

Other comp

</TemplateSlide>

I have other menu component that call Comp.razor on button click

                <MainMenuLink Href="" ActiveClass="page-header-active" HrefMatch="MainMenuLinkMatch.Exact">
                    Dashboard
                </MainMenuLink>

                @**@

                <MainMenuLink Href="contacts" ActiveClass="page-header-active">
                    Contacts
                </MainMenuLink>
                Show<Comp>())">

                <MainMenuLink Href="contacts" ActiveClass="page-header-active">
                    Others
                </MainMenuLink>
                Show<Others>())">

How can write generic and dynamic Show method for button click?

Body:
I learned this yesterday and I am only posting this in case it helps someone.

I have a list of users I display in my Blazor Chat, and the names are actually buttons:

@foreach (SubscriberCallback callback in Names)
{
    <button class="listbutton" @onclick="(Action<EventArgs>) (args =>
    SendPrivateMessageClicked(args, callback.Id))">@callback.Name</button><br />
}

I have this method called SendPrivateMessageClicked, and I need to pass in the Id (Guid) of who to send the message to.

private void SendPrivateMessageClicked(EventArgs args, Guid toId)
{
    // Attempt to find the subscriber
    SubscriberCallback subscriber = SubscriberService.FindSubscriber(toId);

    // Send Private Message Code Removed, but you get the point
}

Css for the link button:

.listbutton
{
    background:none;
    border:none;
    margin:0;
    padding:0;
    cursor: pointer;
    border: none;
    color: limegreen;
    height: 2.4vh;
    font-size: 2vh;
}
.listbutton:focus
{
    outline: none;
}

I love Blazor!


问:
Python group by part of a string
So I'm looking at names of files and some of them have _good and _new suffix at the end. I need to move these files but when I come across a file that has two versions, _good and _new, I only wan the _new files to move.

Here's an example of file names:

```<code>student_homework_good
student_homework_new
house_work_good
school_work_good
commute_good
</code>```

From these files, I don't want student_homework_good to move because student_new exists.
The file names are stored in a list: my_files[]

Any suggestions would be welcomed.

答:
It seems pretty easy. All you need to do, is to check the existence of _new in file name, like

listOfFiles = ['student_homework_new', 'student_homework_good', 'commute_good']
for i in listOfFiles:
    if '_new' in i:
        # code for movement to another directory
```

<p>Any other <code>_good</code> files will remain in the same directory.</p>

<p>If you only want to group them by names, you could do something like</p>

<pre class="lang-py prettyprint-override"><code>goodFiles = [i for i in os.listdir('yourdirectory') if '_good' in i]
newFiles  = [i for i in os.listdir('yourdirectory') if '_new' in i]
</code>```

After grouping, you can move whatever you want to any folder of course.

Title: Python group by part of a string

Body:
So I'm looking at names of files and some of them have _good and _new suffix at the end. I need to move these files but when I come across a file that has two versions, _good and _new, I only wan the _new files to move.

Here's an example of file names:

student_homework_good
student_homework_new
house_work_good
school_work_good
commute_good

From these files, I don't want student_homework_good to move because student_new exists.
The file names are stored in a list: my_files[]

Any suggestions would be welcomed.

Body:
It seems pretty easy. All you need to do, is to check the existence of _new in file name, like

listOfFiles = ['student_homework_new', 'student_homework_good', 'commute_good']
for i in listOfFiles:
    if '_new' in i:
        # code for movement to another directory

Any other _good files will remain in the same directory.

If you only want to group them by names, you could do something like

goodFiles = [i for i in os.listdir('yourdirectory') if '_good' in i]
newFiles  = [i for i in os.listdir('yourdirectory') if '_new' in i]

After grouping, you can move whatever you want to any folder of course.


问:
log4net argument to LogManager.GetLogger
Why do most log4net examples get the logger for a class by doing this:

```<code>private static ILog logger =
    LogManager.GetLogger(
    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
</code>```

Rather than just passing typeof(MyClass):

```<code>private static ILog logger = LogManager.GetLogger(typeof(MyClass));
</code>```

Is there any other reason for doing this, beside the fact that the first option does not require you to type a specific class name?

答: It also makes it easier to create Codesmith templates for code generation purposes.</p>

OwnerDisplayName: Andy White

ContentLicense: CC BY-SA 2.5

Body:
Why do most log4net examples get the logger for a class by doing this:

private static ILog logger =
    LogManager.GetLogger(
    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Rather than just passing typeof(MyClass):

private static ILog logger = LogManager.GetLogger(typeof(MyClass));

Is there any other reason for doing this, beside the fact that the first option does not require you to type a specific class name?


问:
ffmpeg - ffprobe duration format change
I am using ffmpeg to get some file durations
Below is my code

```<code>$filename = '1aef53e6-92ac-4d28-89f8-4cce28fa0f58.mp4'
$duration = if ((ffmpeg -i $filename 2>&1 | Out-String) -match 'Duration:\s+([\d:.]+)') { $matches[1] }
</code>```

Actual output would be like
H :M :S : F
00:00:00.00

I need the output to be like
00:00:00:00
Between seconds and frame, there is a " . " full stop, I need it to be a " : "

any suggestions ?

答:
Add .Replace(".",":") after $matches[1]

$duration = if ((ffmpeg -i $filename 2>&1 | Out-String) -match 'Duration:\s+([\d:.]+)') { $matches[1].Replace(".",":") }

Title: ffmpeg - ffprobe duration format change

Body:
I am using ffmpeg to get some file durations
Below is my code

$filename = '1aef53e6-92ac-4d28-89f8-4cce28fa0f58.mp4'
$duration = if ((ffmpeg -i $filename 2>&1 | Out-String) -match 'Duration:\s+([\d:.]+)') { $matches[1] }

Actual output would be like
H :M :S : F
00:00:00.00

I need the output to be like
00:00:00:00
Between seconds and frame, there is a " . " full stop, I need it to be a " : "

any suggestions ?


问:
Using regex to remove unessential comments from source
This is the expression I have come up with to remove comments from my source code, it removes all comments except browser specific comments.

```<code>/<\!--(?!\[if).*?-->/s
</code>```

I do not 100% understand regex but I managed to "Frankenstein" this together from various expressions I have found while searching through Stack.  This is how I am seeing the breakdown of this expression and I would love if someone could help me understand it further.

```<code>/<\!--
</code>```

Is used to search for the part I want to replace with the slashes to escape the ! since it is part of the expression?

```<code>(?!\[if)
</code>```

Says if does not contain [if block?

```<code> .*?
</code>```

Wildcard so saying no matter what is in between?

```<code>-->
</code>```

The end of the bit I want the expression to find.

```<code>/s
</code>```

Tells the expression to run even if there is white space between the expression?

I don't want to just use a code because it works for what I need, I want to actually understand what I am using and learn how to use it better in the future.

This expression works great, but I do need help taking it one step further.  In my source I have code snippets within script tags I.E.

```<code><script type="text/javascript">
  <!--
    // Main vBulletin Javascript Initialization
    vBulletin_init();
  //-->
</script>
</code>```

Is there a way I can adapt my current expression to exclude

答:
You reached the point where you realized that regex patterns are bad to deal with programming languages. Here, the tool to use is obviously an HTML parser. Example using the DOM and XPath: </p>

```<code>$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXPath($dom);

$comments = $xp->query('//*[not(local-name()="script")]/comment()[not(contains(.,"[if"))]');

foreach($comments as $comment) {
    $comment->parentNode->removeChild($comment);
}

echo $dom->saveHTML();
</code>```

Body:
This is the expression I have come up with to remove comments from my source code, it removes all comments except browser specific comments.

/<\!--(?!\[if).*?-->/s

I do not 100% understand regex but I managed to "Frankenstein" this together from various expressions I have found while searching through Stack.  This is how I am seeing the breakdown of this expression and I would love if someone could help me understand it further.

/<\!--

Is used to search for the part I want to replace with the slashes to escape the ! since it is part of the expression?

(?!\[if)

Says if does not contain [if block?

 .*?

Wildcard so saying no matter what is in between?

-->

The end of the bit I want the expression to find.

/s

Tells the expression to run even if there is white space between the expression?

I don't want to just use a code because it works for what I need, I want to actually understand what I am using and learn how to use it better in the future.

This expression works great, but I do need help taking it one step further.  In my source I have code snippets within script tags I.E.

Is there a way I can adapt my current expression to exclude

Body:
You reached the point where you realized that regex patterns are bad to deal with programming languages. Here, the tool to use is obviously an HTML parser. Example using the DOM and XPath:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXPath($dom);

$comments = $xp->query('//*[not(local-name()="script")]/comment()[not(contains(.,"[if"))]');

foreach($comments as $comment) {
    $comment->parentNode->removeChild($comment);
}

echo $dom->saveHTML();


问:
Setup a GRE tunnel with dedicated IP in GCP VPS instance, CentOS7
I had create a new VPS instance in GCP successfully. Logged in via ssh and take root access. My commands to setting up a tun1 interface was successfull done:

```<code>ip tunnel del tun1
ip tunnel add tun1 mode gre remote xxx.xxx.xxx.xx local xx.xxx.xxx.xxx ttl 255
ip link set tun1 up
ip link set tun1 mtu 1360
ip addr add xxx.xxx.xxx.xx/32 dev lo
ip r add xxx.xxx.xxx.x/32 dev tun1
ip route add default via xxx.xxx.xxx.x dev tun1 table 200
ip rule add from xxx.xxx.xxx.xx table 200
</code>```

If I check with     lsmode | grep gre, I see

```<code># lsmod | grep tun
tun         31740  0
ip_tunnel   25163  1 ip_gre
</code>```

I try also:
    # modprobe ip_tunnel
    # modprobe gre
    #

No results be displayed.

If everything is okay, I should be able to access my server with the external dedicated IP xxx.xxx.xxx.xx (it is a Cloud DNS system).

Push, could anybody out there help me ?

答:
Unfortunately Google doesn't allow GRE traffic.

See here:
https://cloud.google.com/vpc/docs/firewalls#blockedtraffic

Always blocked traffic Google Cloud always blocks the traffic that is
  described in the following table. Your firewall rules cannot be used
  to allow any of this traffic.

Always blocked traffic    Applies to GRE traffic  All sources and
  destinations, whether the source or destination is an internal IP
  address or an external IP address.

Body:
I had create a new VPS instance in GCP successfully. Logged in via ssh and take root access. My commands to setting up a tun1 interface was successfull done:

ip tunnel del tun1
ip tunnel add tun1 mode gre remote xxx.xxx.xxx.xx local xx.xxx.xxx.xxx ttl 255
ip link set tun1 up
ip link set tun1 mtu 1360
ip addr add xxx.xxx.xxx.xx/32 dev lo
ip r add xxx.xxx.xxx.x/32 dev tun1
ip route add default via xxx.xxx.xxx.x dev tun1 table 200
ip rule add from xxx.xxx.xxx.xx table 200

If I check with     lsmode | grep gre, I see

# lsmod | grep tun
tun         31740  0
ip_tunnel   25163  1 ip_gre

I try also:
    # modprobe ip_tunnel
    # modprobe gre
    #

No results be displayed.

If everything is okay, I should be able to access my server with the external dedicated IP xxx.xxx.xxx.xx (it is a Cloud DNS system).

Push, could anybody out there help me ?


问:
python: minimum value within specified bounds for an array
Say I have an array  a = [-1.2, 1, 0.5, 4, 5, 3]

Is there a way to find a min element which is within a=0.2 to b=2

In this particular example the answer will be 0.5.

I want to perform this computation in python. .

答:
You can use filter(predicate, list) or a generator expression to eliminate the out-of-bounds values, then use min(iterable) on the remaining elements:

```<code>a = [-1.2, 1, 0.5, 4, 5, 3]
assert 0.5 == min(filter(lambda x: 0.2 <= x <= 2, a))
# or
assert 0.5 == min(x for x in a if 0.2 <= x <= 2)
</code>```

Body:
You can use filter(predicate, list) or a generator expression to eliminate the out-of-bounds values, then use min(iterable) on the remaining elements:

a = [-1.2, 1, 0.5, 4, 5, 3]
assert 0.5 == min(filter(lambda x: 0.2 <= x <= 2, a))
# or
assert 0.5 == min(x for x in a if 0.2 <= x <= 2)


问:
Node.js returning an error on a colon in JSON array
I am trying to use node.js to read a JSON file server-side and reading it using fs. When I try to parse a JSON file, it works with a single object, but when reading an array, it gives an error on a colon. The server script is in the same directory as the JSON file, and I wrote my JSON file to comply with the directions shown at https://www.json.org/json-en.html.

Javascript code I am trying to run:

```<code>console.log('recived login request');
var obj = fs.readFileSync('userInfo.json');
console.log(JSON.parse(obj));
</code>```

Json file code:

```<code>{ "test": [ "testUno" :"yes" ] }
</code>```

(Note: the json file code shown is just a test)

答: Ok so it turns out I dont know how to write json but now I do. oops</p>

Body:
I am trying to use node.js to read a JSON file server-side and reading it using fs. When I try to parse a JSON file, it works with a single object, but when reading an array, it gives an error on a colon. The server script is in the same directory as the JSON file, and I wrote my JSON file to comply with the directions shown at https://www.json.org/json-en.html.

Javascript code I am trying to run:

console.log('recived login request');
var obj = fs.readFileSync('userInfo.json');
console.log(JSON.parse(obj));

Json file code:

{ "test": [ "testUno" :"yes" ] }

(Note: the json file code shown is just a test)


问:
LXC - Failed to create macvlan interface - Operation not permitted
I am having problem to create a LXC container over OpenVZ server, I am getting the error bellow when lxc try to create an interface. I am not sure if OpenVZ permit this kind of configuration, it is my first time trying. I have looking for some solution on the internet, but I didn't find anything to solve my problem. I appreciate any help. Thanks.

root@websrv:~# lxc launch ubuntu:18.04 ubuntu

Creating ubuntu
Starting ubuntu
Error: Failed to run: /usr/lib/lxd/lxd forkstart ubuntu /var/lib/lxd/containers /var/log/lxd/ubuntu/lxc.conf:
Try lxc info --show-log local:ubuntu for more info
root@websrv:~# lxc info --show-log local:ubuntu
Name: ubuntu
Remote: unix://
Architecture: x86_64
Created: 2020/06/01 20:48 UTC
Status: Stopped
Type: persistent
Profiles: default

Log:

lxc ubuntu 20200601204903.730 ERROR    network - network.c:instantiate_macvlan:234 - Operation not permitted - Failed to create macvlan interface "mcHNUAG7" on "venet0"
lxc ubuntu 20200601204903.730 ERROR    network - network.c:lxc_create_network_priv:2457 - Failed to create network device
lxc ubuntu 20200601204903.730 ERROR    start - start.c:lxc_spawn:1626 - Failed to create the network
lxc ubuntu 20200601204903.730 ERROR    start - start.c:__lxc_start:1939 - Failed to spawn container "ubuntu"
lxc ubuntu 20200601204903.733 ERROR    lxccontainer - lxccontainer.c:wait_on_daemonized_start:842 - Received container state "STOPPING" instead of "RUNNING"
lxc 20200601204903.765 WARN     commands - commands.c:lxc_cmd_rsp_recv:132 - Connection reset by peer - Failed to receive response for command "get_state"

答: I just found that is better have KVM VPS if you are planning to use LXC or Docker. OpenVZ have few limitation.</p>


问:
Python 3.6.1 crashed after readline module installed
I've compiled and installed Python 3.6.1 from source code, and run sudo pip3 install readline to install the readline module. But when I start the Python shell, it crashes whatever I enter:

```<code>Python 3.6.1 (default, Mar 25 2017, 13:40:56)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello")
*** Error in `python3': munmap_chunk(): invalid pointer: 0x00007fa3c64960a0 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fa3c565e7e5]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x1a8)[0x7fa3c566aae8]
python3(PyOS_Readline+0xec)[0x5c3bcc]
python3[0x447cd0]
python3[0x449788]
python3(PyTokenizer_Get+0x9)[0x44a659]
python3[0x44617e]
python3(PyParser_ASTFromFileObject+0xa3)[0x428803]
python3(PyRun_InteractiveOneObject+0x122)[0x428a42]
python3(PyRun_InteractiveLoopFlags+0x6e)[0x428dce]
python3(PyRun_AnyFileExFlags+0x3c)[0x428efc]
python3(Py_Main+0xe4f)[0x43ba3f]
python3(main+0x162)[0x41dc52]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fa3c5607830]
python3(_start+0x29)[0x41dd29]
======= Memory map: ========
00400000-00663000 r-xp 00000000 08:05 16779642                           /usr/local/bin/python3.6
00862000-00863000 r--p 00262000 08:05 16779642                           /usr/local/bin/python3.6
00863000-008c7000 rw-p 00263000 08:05 16779642                           /usr/local/bin/python3.6
008c7000-008f7000 rw-p 00000000 00:00 0
00d60000-00e31000 rw-p 00000000 00:00 0                                  [heap]
7fa3c4a96000-7fa3c4aac000 r-xp 00000000 08:05 528788                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fa3c4aac000-7fa3c4cab000 ---p 00016000 08:05 528788                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fa3c4cab000-7fa3c4cac000 rw-p 00015000 08:05 528788                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fa3c4cac000-7fa3c4cec000 rw-p 00000000 00:00 0
7fa3c4cec000-7fa3c4d11000 r-xp 00000000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4d11000-7fa3c4f10000 ---p 00025000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4f10000-7fa3c4f14000 r--p 00024000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4f14000-7fa3c4f15000 rw-p 00028000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4f15000-7fa3c4f52000 r-xp 00000000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c4f52000-7fa3c5151000 ---p 0003d000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c5151000-7fa3c5153000 r--p 0003c000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c5153000-7fa3c515a000 rw-p 0003e000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c515a000-7fa3c515c000 rw-p 00000000 00:00 0
7fa3c515c000-7fa3c55e7000 r--p 00000000 08:05 16253117                   /usr/lib/locale/locale-archive
7fa3c55e7000-7fa3c57a6000 r-xp 00000000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c57a6000-7fa3c59a6000 ---p 001bf000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c59a6000-7fa3c59aa000 r--p 001bf000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c59aa000-7fa3c59ac000 rw-p 001c3000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c59ac000-7fa3c59b0000 rw-p 00000000 00:00 0
7fa3c59b0000-7fa3c5ab8000 r-xp 00000000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5ab8000-7fa3c5cb7000 ---p 00108000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5cb7000-7fa3c5cb8000 r--p 00107000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5cb8000-7fa3c5cb9000 rw-p 00108000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5cb9000-7fa3c5cbb000 r-xp 00000000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5cbb000-7fa3c5eba000 ---p 00002000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5eba000-7fa3c5ebb000 r--p 00001000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5ebb000-7fa3c5ebc000 rw-p 00002000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5ebc000-7fa3c5ebf000 r-xp 00000000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c5ebf000-7fa3c60be000 ---p 00003000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c60be000-7fa3c60bf000 r--p 00002000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c60bf000-7fa3c60c0000 rw-p 00003000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c60c0000-7fa3c60d8000 r-xp 00000000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c60d8000-7fa3c62d7000 ---p 00018000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c62d7000-7fa3c62d8000 r--p 00017000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c62d8000-7fa3c62d9000 rw-p 00018000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c62d9000-7fa3c62dd000 rw-p 00000000 00:00 0
7fa3c62dd000-7fa3c6303000 r-xp 00000000 08:05 524634                     /lib/x86_64-linux-gnu/ld-2.23.so
7fa3c6339000-7fa3c64e2000 rw-p 00000000 00:00 0
7fa3c64f8000-7fa3c64f9000 rw-p 00000000 00:00 0
7fa3c64f9000-7fa3c6500000 r--s 00000000 08:05 16522416                   /usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache
7fa3c6500000-7fa3c6502000 rw-p 00000000 00:00 0
7fa3c6502000-7fa3c6503000 r--p 00025000 08:05 524634                     /lib/x86_64-linux-gnu/ld-2.23.so
7fa3c6503000-7fa3c6504000 rw-p 00026000 08:05 524634                     /lib/x86_64-linux-gnu/ld-2.23.so
7fa3c6504000-7fa3c6505000 rw-p 00000000 00:00 0
7ffcb1700000-7ffcb1721000 rw-p 00000000 00:00 0                          [stack]
7ffcb17ad000-7ffcb17af000 r--p 00000000 00:00 0                          [vvar]
7ffcb17af000-7ffcb17b1000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)
</code>```

What's the matter here? I'm using Ubuntu 16.04.

答:
Mac:

```<code>pip install readline
</code>```

Windows:

```<code>pip install pyreadline
</code>```

Unix:

```<code>pip install gnureadline
</code>```

Body:
I've compiled and installed Python 3.6.1 from source code, and run sudo pip3 install readline to install the readline module. But when I start the Python shell, it crashes whatever I enter:

Python 3.6.1 (default, Mar 25 2017, 13:40:56)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello")
*** Error in `python3': munmap_chunk(): invalid pointer: 0x00007fa3c64960a0 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fa3c565e7e5]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x1a8)[0x7fa3c566aae8]
python3(PyOS_Readline+0xec)[0x5c3bcc]
python3[0x447cd0]
python3[0x449788]
python3(PyTokenizer_Get+0x9)[0x44a659]
python3[0x44617e]
python3(PyParser_ASTFromFileObject+0xa3)[0x428803]
python3(PyRun_InteractiveOneObject+0x122)[0x428a42]
python3(PyRun_InteractiveLoopFlags+0x6e)[0x428dce]
python3(PyRun_AnyFileExFlags+0x3c)[0x428efc]
python3(Py_Main+0xe4f)[0x43ba3f]
python3(main+0x162)[0x41dc52]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fa3c5607830]
python3(_start+0x29)[0x41dd29]
======= Memory map: ========
00400000-00663000 r-xp 00000000 08:05 16779642                           /usr/local/bin/python3.6
00862000-00863000 r--p 00262000 08:05 16779642                           /usr/local/bin/python3.6
00863000-008c7000 rw-p 00263000 08:05 16779642                           /usr/local/bin/python3.6
008c7000-008f7000 rw-p 00000000 00:00 0
00d60000-00e31000 rw-p 00000000 00:00 0                                  [heap]
7fa3c4a96000-7fa3c4aac000 r-xp 00000000 08:05 528788                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fa3c4aac000-7fa3c4cab000 ---p 00016000 08:05 528788                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fa3c4cab000-7fa3c4cac000 rw-p 00015000 08:05 528788                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fa3c4cac000-7fa3c4cec000 rw-p 00000000 00:00 0
7fa3c4cec000-7fa3c4d11000 r-xp 00000000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4d11000-7fa3c4f10000 ---p 00025000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4f10000-7fa3c4f14000 r--p 00024000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4f14000-7fa3c4f15000 rw-p 00028000 08:05 528922                     /lib/x86_64-linux-gnu/libtinfo.so.5.9
7fa3c4f15000-7fa3c4f52000 r-xp 00000000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c4f52000-7fa3c5151000 ---p 0003d000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c5151000-7fa3c5153000 r--p 0003c000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c5153000-7fa3c515a000 rw-p 0003e000 08:05 16786336                   /usr/local/lib/python3.6/site-packages/readline.cpython-36m-x86_64-linux-gnu.so
7fa3c515a000-7fa3c515c000 rw-p 00000000 00:00 0
7fa3c515c000-7fa3c55e7000 r--p 00000000 08:05 16253117                   /usr/lib/locale/locale-archive
7fa3c55e7000-7fa3c57a6000 r-xp 00000000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c57a6000-7fa3c59a6000 ---p 001bf000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c59a6000-7fa3c59aa000 r--p 001bf000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c59aa000-7fa3c59ac000 rw-p 001c3000 08:05 524633                     /lib/x86_64-linux-gnu/libc-2.23.so
7fa3c59ac000-7fa3c59b0000 rw-p 00000000 00:00 0
7fa3c59b0000-7fa3c5ab8000 r-xp 00000000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5ab8000-7fa3c5cb7000 ---p 00108000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5cb7000-7fa3c5cb8000 r--p 00107000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5cb8000-7fa3c5cb9000 rw-p 00108000 08:05 524562                     /lib/x86_64-linux-gnu/libm-2.23.so
7fa3c5cb9000-7fa3c5cbb000 r-xp 00000000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5cbb000-7fa3c5eba000 ---p 00002000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5eba000-7fa3c5ebb000 r--p 00001000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5ebb000-7fa3c5ebc000 rw-p 00002000 08:05 524647                     /lib/x86_64-linux-gnu/libutil-2.23.so
7fa3c5ebc000-7fa3c5ebf000 r-xp 00000000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c5ebf000-7fa3c60be000 ---p 00003000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c60be000-7fa3c60bf000 r--p 00002000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c60bf000-7fa3c60c0000 rw-p 00003000 08:05 524547                     /lib/x86_64-linux-gnu/libdl-2.23.so
7fa3c60c0000-7fa3c60d8000 r-xp 00000000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c60d8000-7fa3c62d7000 ---p 00018000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c62d7000-7fa3c62d8000 r--p 00017000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c62d8000-7fa3c62d9000 rw-p 00018000 08:05 524644                     /lib/x86_64-linux-gnu/libpthread-2.23.so
7fa3c62d9000-7fa3c62dd000 rw-p 00000000 00:00 0
7fa3c62dd000-7fa3c6303000 r-xp 00000000 08:05 524634                     /lib/x86_64-linux-gnu/ld-2.23.so
7fa3c6339000-7fa3c64e2000 rw-p 00000000 00:00 0
7fa3c64f8000-7fa3c64f9000 rw-p 00000000 00:00 0
7fa3c64f9000-7fa3c6500000 r--s 00000000 08:05 16522416                   /usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache
7fa3c6500000-7fa3c6502000 rw-p 00000000 00:00 0
7fa3c6502000-7fa3c6503000 r--p 00025000 08:05 524634                     /lib/x86_64-linux-gnu/ld-2.23.so
7fa3c6503000-7fa3c6504000 rw-p 00026000 08:05 524634                     /lib/x86_64-linux-gnu/ld-2.23.so
7fa3c6504000-7fa3c6505000 rw-p 00000000 00:00 0
7ffcb1700000-7ffcb1721000 rw-p 00000000 00:00 0                          [stack]
7ffcb17ad000-7ffcb17af000 r--p 00000000 00:00 0                          [vvar]
7ffcb17af000-7ffcb17b1000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)

What's the matter here? I'm using Ubuntu 16.04.

Body:
Mac:

pip install readline

Windows:

pip install pyreadline

Unix:

pip install gnureadline


问:
jQuery check/uncheck radio button onclick
I have this code to check/uncheck a radio button onclick.

I know it is not good for the UI, but I need this.

```<code>$('#radioinstant').click(function() {
  var checked = $(this).attr('checked', true);
  if(checked){
    $(this).attr('checked', false);
  }
  else{
    $(this).attr('checked', true);
  }
});
</code>```

The above function is not working.

If I click on the button, nothing changes. It remain checked. Why? Where is the error? I am not a jQuery expert. I am on jQuery 1.3.2

Just to be clear #radioinstant is the ID of the radio button.

答:
        $(document).on("click", "input[type='radio']", function(e) {
            var checked = $(this).attr("checked");
            if(!checked){
                $(this).attr("checked", true);
            } else {
                $(this).removeAttr("checked");
                $(this).prop("checked", false);
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" id="radio" /> <label for="radio">Radio</label></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code to check/uncheck a radio button onclick.

I know it is not good for the UI, but I need this.

$('#radioinstant').click(function() {
  var checked = $(this).attr('checked', true);
  if(checked){
    $(this).attr('checked', false);
  }
  else{
    $(this).attr('checked', true);
  }
});

The above function is not working.

If I click on the button, nothing changes. It remain checked. Why? Where is the error? I am not a jQuery expert. I am on jQuery 1.3.2

Just to be clear #radioinstant is the ID of the radio button.

Body:
        $(document).on("click", "input[type='radio']", function(e) {
            var checked = $(this).attr("checked");
            if(!checked){
                $(this).attr("checked", true);
            } else {
                $(this).removeAttr("checked");
                $(this).prop("checked", false);
            }
        });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" id="radio" /> <label for="radio">Radio</label>


问:
'ContentView_Previews' is not a member type of error
'ContentView_Previews' does not compile if ContentView references an external object.

If I remove all references to @ObservedObject, preview compiles.

```<code>import SwiftUI

struct ContentView: View {

    @ObservedObject var fancyTimer = FancyTimer()

    var body: some View {

    Text("\(fancyTimer.timerValue)")
       .font(.largeTitle)
    }
}

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

import Foundation
import SwiftUI
import Combine

class FancyTimer: ObservableObject {

    @Published var timerValue: Int = 0

    init() {

        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true)
        { timer in
           self.timerValue += 1
        }
     }
   }
</code>```

Error is: 'ContentView' is not a member type of 'FancyTimer'

答: My projectname was the same as one of the Foundation's classes. Changing the Projectname fixed the issue. </p>

Body:
'ContentView_Previews' does not compile if ContentView references an external object.

If I remove all references to @ObservedObject, preview compiles.

import SwiftUI

struct ContentView: View {

    @ObservedObject var fancyTimer = FancyTimer()

    var body: some View {

    Text("\(fancyTimer.timerValue)")
       .font(.largeTitle)
    }
}

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

import Foundation
import SwiftUI
import Combine

class FancyTimer: ObservableObject {

    @Published var timerValue: Int = 0

    init() {

        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true)
        { timer in
           self.timerValue += 1
        }
     }
   }

Error is: 'ContentView' is not a member type of 'FancyTimer'


问:
How can I retrieve the attribute of a clicked element with jQuery?
I'm using wordpress and woocommerce, and I want to add some scripts to run when a product variation is selected, with jQuery.

I have a set of "buttons" in html like this:

```<code><div class="adsw-attribute-option">
  <span class="meta-item-text sku-set" data-value="s">S</span>
  <span class="meta-item-text sku-set" data-value="m">M</span>
  <span class="meta-item-text sku-set" data-value="l">L</span>
  <span class="meta-item-text sku-set" data-value="xl">XL</span>
  <span class="meta-item-text sku-set" data-value="xxl">XXL</span>
  <span class="meta-item-text sku-set" data-value="xxxl">XXXL</span>
</div>
</code>```

I add click listeners with the following:

```<code>$(".adsw-attribute-option > .meta-item-text").on("click", () => {})
</code>```

And inside the handler I need to read the data-value attribute of the "button" that was clicked. First I tried: $(this).attr("data-value"). This returned undefined. I've tried with .data instead of the attr function, with the same result.

It seems like there's some issue with the usage of $(this), I couldn't read any of its properties like html, or class.

I thought $(this) should refer to the object, that the event was called on, but it seems, this is not the case.

What am I missing here? Is there any other way to retrieve the value of "data-value" in this case?

答:
You should use the .attr function:

$(".adsw-attribute-option > .meta-item-text").on("click", function () {
  $(this).attr('data-value');
});
```

It's important you don't use an arrow function because you can't call this when using an arrow function.

Body:
I'm using wordpress and woocommerce, and I want to add some scripts to run when a product variation is selected, with jQuery.

I have a set of "buttons" in html like this:

  S
  M
  L
  XL
  XXL
  XXXL

I add click listeners with the following:

$(".adsw-attribute-option > .meta-item-text").on("click", () => {})

And inside the handler I need to read the data-value attribute of the "button" that was clicked. First I tried: $(this).attr("data-value"). This returned undefined. I've tried with .data instead of the attr function, with the same result.

It seems like there's some issue with the usage of $(this), I couldn't read any of its properties like html, or class.

I thought $(this) should refer to the object, that the event was called on, but it seems, this is not the case.

What am I missing here? Is there any other way to retrieve the value of "data-value" in this case?

Body:
You should use the .attr function:

$(".adsw-attribute-option > .meta-item-text").on("click", function () {
  $(this).attr('data-value');
});

It's important you don't use an arrow function because you can't call this when using an arrow function.


问:
Java jsp sends servlet null variables
So I have this piece of code in my .jsp file

```<code><table border="0" style="width:400px;">
    <form class="Credentials" action="SellerServlet" method="post">
        <tr style="height: 40px">method
            #User name
            <td style="width: 20%; text-align: right;">
                <label for="Name"><b>Name:</b></label>
            </td>
            <td>
                <input type="text" id="Name" name="Name" required>
            </td>
        </tr>

        #Surname
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;" >
                <label for="surname"><b>Surname:</b></label>
            </td>
            <td>
                <input type="text" id="Surname" name="Surname" required>
            </td>
        </tr>

        #Username
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;">
                <label for="username"><b>Username:</b></label>
            </td>
            <td>
                <input  type="text" id="username" name="user" required>
            </td>
        </tr>
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;" >
                <label for="password"><b>Password:</b></label>
            </td>
            <td>
                <input type="password" id="password" name="pass" required>
            </td>
        </tr>

        #User Type
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;" >
                <label for="type"><b>Type:</b></label>
            </td>
            <td>
                <input type="text" id="type" placeholder="Client" readonly>
            </td>
        </tr>

        #User Program
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;"  >
                <label for="program"><b>Program:</b></label>
            </td>
            <td>
                <select style="width: 150px" id="program" name="program" >
                    <option value="" selected disabled hidden>Επιλέξτε πρόγραμμα</option>
                    <option>asdfs</option>
                    <option>asdfas</option>
                    <option>asfdas</option>
                </select>
            </td>
        </tr>

        #Submit Button
        <tr style="height: 100px;">
            <td colspan="2" style="width: 50%">
                <center>
                    <button type="submit" name="Register" >Register</button>
                </center>
            </td>
        </tr>
    </form>
</table>
</code>```

And my servlet code is

```<code>@WebServlet(name = "SellerServlet" , urlPatterns = {"/SellerServlet"})
public class SellerServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String registerButton = request.getParameter("register");
        if(registerButton!=null){
            //request.getRequestDispatcher("/index.jsp").forward(request, response);
            String Username=request.getParameter("user");
            String Password=request.getParameter("pass");
            System.out.println(Username+Password);
            Seller CreateClient= new Seller();
            CreateClient.CreateClientAccount(Username,Password);
        }
    }
}
</code>```

What the servlet here is supposed to do is pass the 2 values (user and pass) to an object of the class Seller to later do something with them, I didn't include that following part because it works it just gets the value of null from both and I have broken my head for 2 hours now trying to figure out why

In case needed: Using java 14 and tomcat 9

答:
What does this variable relate to?

```<code>String registerButton = request.getParameter("register");
  if(registerButton!=null){
</code>```

If with

```<code><button type="submit" name="Register" >Register</button>
</code>```

The name is incorrect(Register vs register) and you do not need to check value of this button, just click the button submit and the form will do everything for you. you just need to get the passed arguments(ex, request.getParameter(user)).
You don't get its value and just remove it from the code

Title: Java jsp sends servlet null variables

Body:
So I have this piece of code in my .jsp file

    <form class="Credentials" action="SellerServlet" method="post">

method
            #User name

                Name:

                <input type="text" id="Name" name="Name" required>

        #Surname

                Surname:

                <input type="text" id="Surname" name="Surname" required>

        #Username

                Username:

                <input  type="text" id="username" name="user" required>

                Password:

                <input type="password" id="password" name="pass" required>

        #User Type

                Type:

                <input type="text" id="type" placeholder="Client" readonly>

        #User Program

                Program:

                <select style="width: 150px" id="program" name="program" >
                    <option value="" selected disabled hidden>Επιλέξτε πρόγραμμα</option>
                    <option>asdfs</option>
                    <option>asdfas</option>
                    <option>asfdas</option>
                </select>

        #Submit Button

                    <button type="submit" name="Register" >Register</button>

    </form>

And my servlet code is

@WebServlet(name = "SellerServlet" , urlPatterns = {"/SellerServlet"})
public class SellerServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String registerButton = request.getParameter("register");
        if(registerButton!=null){
            //request.getRequestDispatcher("/index.jsp").forward(request, response);
            String Username=request.getParameter("user");
            String Password=request.getParameter("pass");
            System.out.println(Username+Password);
            Seller CreateClient= new Seller();
            CreateClient.CreateClientAccount(Username,Password);
        }
    }
}

What the servlet here is supposed to do is pass the 2 values (user and pass) to an object of the class Seller to later do something with them, I didn't include that following part because it works it just gets the value of null from both and I have broken my head for 2 hours now trying to figure out why

In case needed: Using java 14 and tomcat 9

Body:
What does this variable relate to?

String registerButton = request.getParameter("register");
  if(registerButton!=null){

If with

<button type="submit" name="Register" >Register</button>

The name is incorrect(Register vs register) and you do not need to check value of this button, just click the button submit and the form will do everything for you. you just need to get the passed arguments(ex, request.getParameter(user)).
You don't get its value and just remove it from the code


问:
Cloudformation error: Property validation failure: [Encountered unsupported properties in {/}: [UserData]]
Been trying to create a cloud formation template. I have been trying to use the UserData section and have reduced the template to the bones to identify what the problem is:

I am getting the error: Property validation failure: [Encountered unsupported properties in {/}: [UserData]]

This is my now totally barebones template. I must be doing something fundamentally wrong. Can someone help please?

```<code>    {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "319ac38d-a9ea-4855-9a9a-4dc91f6ef092": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": -310,
                    "y": 30
                },
                "z": 1,
                "embeds": []
            }
        }
    },
    "Resources": {
        "Cloud9Template": {
            "Type": "AWS::Cloud9::EnvironmentEC2",
            "Properties": {
                "UserData":{
                    "Fn::Base64" : {
                        "Fn::Join" : [ ",", [
                            "test",
                            "Hello World" ] ]
                    }
                },
                "AutomaticStopTimeMinutes": "45",
                "InstanceType": "t2.micro",
                "Name": {
                    "Ref": "AWS::StackName"
                }
            },
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "319ac38d-a9ea-4855-9a9a-4dc91f6ef092"
                },
                "AWS::CloudFormation::Init" : {
                    "sources" : {
                      "/home/ec2-user/environment/src" : <linktotarball>"
                    }
                }
            }
        }
    }
}
</code>```

Thank you!

答:
Unfortunately, AWS::Cloud9::EnvironmentEC2 does not support UserData as shown in its documentation.

In other words, you can't use UserData in the definition of EnvironmentEC2 resource.

Body:
Been trying to create a cloud formation template. I have been trying to use the UserData section and have reduced the template to the bones to identify what the problem is:

I am getting the error: Property validation failure: [Encountered unsupported properties in {/}: [UserData]]

This is my now totally barebones template. I must be doing something fundamentally wrong. Can someone help please?

    {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "319ac38d-a9ea-4855-9a9a-4dc91f6ef092": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": -310,
                    "y": 30
                },
                "z": 1,
                "embeds": []
            }
        }
    },
    "Resources": {
        "Cloud9Template": {
            "Type": "AWS::Cloud9::EnvironmentEC2",
            "Properties": {
                "UserData":{
                    "Fn::Base64" : {
                        "Fn::Join" : [ ",", [
                            "test",
                            "Hello World" ] ]
                    }
                },
                "AutomaticStopTimeMinutes": "45",
                "InstanceType": "t2.micro",
                "Name": {
                    "Ref": "AWS::StackName"
                }
            },
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "319ac38d-a9ea-4855-9a9a-4dc91f6ef092"
                },
                "AWS::CloudFormation::Init" : {
                    "sources" : {
                      "/home/ec2-user/environment/src" : <linktotarball>"
                    }
                }
            }
        }
    }
}

Thank you!


问:
Is there a way to connect my Flutter web application to DB located on a server?
Hello dear fellow programmers.
I hope the title explains my question enough. But just in case...

When I connect to a databse using SQL package in my mobile app, there is really no problem. When I try to use the same code in my Flutter web app, I get this error: "Unsupported operation: Socket constructor".

I've spent a good few hours looking for any kind of solution online, but I couldn't find any. That's why I am asking here.

Thank you.

答: As I know some database packages doesn't work with web but some does, you can search sql packages according to web based in here. And I suggest moor to use by only personal opinion.</p>


问:
Is there a way to get rid of the spacing between expansion panels when expanded in an expansion panel list in Flutter?
I am running into a problem where I am wanting to remove the space between expansion panels of an expansion panel list when the panels are expanded.

Images of unwanted behavior, these images are taken from flutter documentation:

List when not expanded, which is fine:

List when expanded:
- You can see the gap between the sections. This is what I do not want for my app.

Any tips are appreciated.

答:
Try Modifying The Actual Implementations

If you have some prior programming experience, this should make sense...

Find these files:

expansion_panel.dart

expansion_title.dart

expand_icon.dart

mergeable_material.dart

These files should be located in the External Library > Dart  Packages > Flutter > src > material. Note that the material folder may be expressed as "src.material".

Android Studio should allow you to hover over the ExpansionPanel Widget and right-click it. After right-clicking it you should see a list of shortcuts, one being "Go to". Click on the "Go to" option which should bring up more options, one of which being "Implementation(s)". This should bring you to where you need. According to my version, double clicking the widget name so the entire widget's name is highlighted should allow for a keyboard shortcut Ctrl+Alt+B.

The key file you must go into is "mergeable_material.dart". In "mergeable.dart", go to the MaterialGap constructor:

```<code>const MaterialGap({
    @required LocalKey key,
    this.size = 16.0,
    //This is the size of the gap between ExpansionTiles WHEN EXPANDED
}) : assert(key != null),
   super(key);
</code>```

This size variable controls the gap between the Expansion Tiles ONLY when EXPANDED. Setting "this.size = 0.0" should remove the gap.

If you want to know why this is, long story short, when the ExpansionPanels list of widgets property is being defined (which is in expansion_panel.dart) a "MaterialGap" is being added between the children. We modified the material gap to be 0.0 thus effectively removing the gap.

Other things you can do:

Change the Trailing Icon in the Header.

Go to expand.dart file. Go to the bottom of the file where the build method should be. In the return statement, replace the icon button with 'whatever' you want (within reason).

```<code>@override
Widget build(BuildContext context) {
  assert(debugCheckHasMaterial(context));
  assert(debugCheckHasMaterialLocalizations(context));
  final MaterialLocalizations localizations = MaterialLocalizations.of(context);
  final String onTapHint = widget.isExpanded ? localizations.expandedIconTapHint :
  localizations.collapsedIconTapHint;

  return Semantics(
    onTapHint: widget.onPressed == null ? null : onTapHint,
    child: Container() //Replaced the Icon Button here to remove it
  );
}
</code>```

Keep in mind that without a button, you must make canTapOnHeader: true, or you won't
  be able to expand the panel. You can make sure you don't forget to do this by going
  to the ExpansionPanel constructor and changing "this.canTapOnHeader = false;" to
  "this.canTapOnHeader = true;

```<code>  ExpansionPanel({
    @required this.headerBuilder,
    @required this.body,
    this.isExpanded = false,
    this.canTapOnHeader = true, //Changed this to true from false
  }) : assert(headerBuilder != null),
       assert(body != null),
       assert(isExpanded != null),
       assert(canTapOnHeader != null);
</code>```

Remove the shadow and/or dividers

Go to the bottom of the expansion_panel.dart file. This is where the build method should be. At the bottom of the build method should be the return statement, which returns MergeableMaterial. You can do the following:

```<code>  return MergeableMaterial(
    hasDividers: false, //Change the boolean value of this
    children: items,
    elevation: 0,
    //Add this line to remove shadow from elevation, REQUIRES ANOTHER STEP
  );
</code>```

If add the "elevation: 0" property you MUST go back to mergeable_material.dart and add the following line of code:

```<code>void _paintShadows(Canvas canvas, Rect rect) {
    if (boxShadows == null) return; //ADD THIS LINE OF CODE
    for (BoxShadow boxShadow in boxShadows) {
      final Paint paint = boxShadow.toPaint();
      // TODO(dragostis): Right now, we are only interpolating the border radii
      // of the visible Material slices, not the shadows; they are not getting
      // interpolated and always have the same rounded radii. Once shadow
      // performance is better, shadows should be redrawn every single time the
      // slices' radii get interpolated and use those radii not the defaults.
      canvas.drawRRect(kMaterialEdges[MaterialType.card].toRRect(rect), paint);
    }
}
</code>```

I think you get the idea, You can do more to remove padding and whatnot by messing around with constants.

Concerns

Note: I'm relatively new to flutter, (2 months last summer and 2 months now- I'm a college student) in fact. I don't know how modifying these files may impact other widgets but I haven't noticed any issues by doing this.
This is also my first post so take it with a grain of salt. Modifying Material implementations may break some rules or conventions that I would refer to the documentation for.

Body:
Try Modifying The Actual Implementations

If you have some prior programming experience, this should make sense...

Find these files:

expansion_panel.dart

expansion_title.dart

expand_icon.dart

mergeable_material.dart

These files should be located in the External Library > Dart  Packages > Flutter > src > material. Note that the material folder may be expressed as "src.material".

Android Studio should allow you to hover over the ExpansionPanel Widget and right-click it. After right-clicking it you should see a list of shortcuts, one being "Go to". Click on the "Go to" option which should bring up more options, one of which being "Implementation(s)". This should bring you to where you need. According to my version, double clicking the widget name so the entire widget's name is highlighted should allow for a keyboard shortcut Ctrl+Alt+B.

The key file you must go into is "mergeable_material.dart". In "mergeable.dart", go to the MaterialGap constructor:

const MaterialGap({
    @required LocalKey key,
    this.size = 16.0,
    //This is the size of the gap between ExpansionTiles WHEN EXPANDED
}) : assert(key != null),
   super(key);

This size variable controls the gap between the Expansion Tiles ONLY when EXPANDED. Setting "this.size = 0.0" should remove the gap.

If you want to know why this is, long story short, when the ExpansionPanels list of widgets property is being defined (which is in expansion_panel.dart) a "MaterialGap" is being added between the children. We modified the material gap to be 0.0 thus effectively removing the gap.

Other things you can do:

Change the Trailing Icon in the Header.

Go to expand.dart file. Go to the bottom of the file where the build method should be. In the return statement, replace the icon button with 'whatever' you want (within reason).

@override
Widget build(BuildContext context) {
  assert(debugCheckHasMaterial(context));
  assert(debugCheckHasMaterialLocalizations(context));
  final MaterialLocalizations localizations = MaterialLocalizations.of(context);
  final String onTapHint = widget.isExpanded ? localizations.expandedIconTapHint :
  localizations.collapsedIconTapHint;

  return Semantics(
    onTapHint: widget.onPressed == null ? null : onTapHint,
    child: Container() //Replaced the Icon Button here to remove it
  );
}

Keep in mind that without a button, you must make canTapOnHeader: true, or you won't
  be able to expand the panel. You can make sure you don't forget to do this by going
  to the ExpansionPanel constructor and changing "this.canTapOnHeader = false;" to
  "this.canTapOnHeader = true;

  ExpansionPanel({
    @required this.headerBuilder,
    @required this.body,
    this.isExpanded = false,
    this.canTapOnHeader = true, //Changed this to true from false
  }) : assert(headerBuilder != null),
       assert(body != null),
       assert(isExpanded != null),
       assert(canTapOnHeader != null);

Remove the shadow and/or dividers

Go to the bottom of the expansion_panel.dart file. This is where the build method should be. At the bottom of the build method should be the return statement, which returns MergeableMaterial. You can do the following:

  return MergeableMaterial(
    hasDividers: false, //Change the boolean value of this
    children: items,
    elevation: 0,
    //Add this line to remove shadow from elevation, REQUIRES ANOTHER STEP
  );

If add the "elevation: 0" property you MUST go back to mergeable_material.dart and add the following line of code:

void _paintShadows(Canvas canvas, Rect rect) {
    if (boxShadows == null) return; //ADD THIS LINE OF CODE
    for (BoxShadow boxShadow in boxShadows) {
      final Paint paint = boxShadow.toPaint();
      // TODO(dragostis): Right now, we are only interpolating the border radii
      // of the visible Material slices, not the shadows; they are not getting
      // interpolated and always have the same rounded radii. Once shadow
      // performance is better, shadows should be redrawn every single time the
      // slices' radii get interpolated and use those radii not the defaults.
      canvas.drawRRect(kMaterialEdges[MaterialType.card].toRRect(rect), paint);
    }
}

I think you get the idea, You can do more to remove padding and whatnot by messing around with constants.

Concerns

Note: I'm relatively new to flutter, (2 months last summer and 2 months now- I'm a college student) in fact. I don't know how modifying these files may impact other widgets but I haven't noticed any issues by doing this.
This is also my first post so take it with a grain of salt. Modifying Material implementations may break some rules or conventions that I would refer to the documentation for.


问:
How do I combine the top n rows with a summary function the remaining rows in R
I wonder if there is an easy way to do the following, perhaps using dplyr:

The data in R built-in dataset "women" is:

```<code>    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   63  129
7   64  132
8   65  135
9   66  139
10  67  142
11  68  146
12  69  150
13  70  154
14  71  159
15  72  164
</code>```

I need a function that would give me, for instance, the first 5 rows combined with the average of the remaining rows, like this:

```<code>    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   67.5    145   # average of the remaining 10 rows
</code>```

答:
Here's an approach with dplyr:

```<code>women %>%
  group_by(group = c(1:5,rep(6,n()-5))) %>%
  summarize_all(mean)
# A tibble: 6 x 3
  group height weight
  <dbl>  <dbl>  <dbl>
1     1   58      115
2     2   59      117
3     3   60      120
4     4   61      123
5     5   62      126
6     6   67.5    145
</code>```

Body:
I wonder if there is an easy way to do the following, perhaps using dplyr:

The data in R built-in dataset "women" is:

    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   63  129
7   64  132
8   65  135
9   66  139
10  67  142
11  68  146
12  69  150
13  70  154
14  71  159
15  72  164

I need a function that would give me, for instance, the first 5 rows combined with the average of the remaining rows, like this:

    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   67.5    145   # average of the remaining 10 rows

Body:
Here's an approach with dplyr:

women %>%
  group_by(group = c(1:5,rep(6,n()-5))) %>%
  summarize_all(mean)
# A tibble: 6 x 3
  group height weight
  <dbl>  <dbl>  <dbl>
1     1   58      115
2     2   59      117
3     3   60      120
4     4   61      123
5     5   62      126
6     6   67.5    145


问:
Angular 9 routing anonymous parameters
I'm working in Angular 9, and trying to capture a route with unknown number of parameters in the URL to express a nested folder structure.

An example group would look like this: /group/:groupId/child1/childofchild1/childofchildofchild1

I don't know how many parameters would follow the :groupId parameter.

Right now, I have a route like this in app.module.ts

```<code>RouterModule.forRoot([
      { path: 'group/:groupId', component: GroupComponent, pathMatch: 'prefix' },
]);
</code>```

This will match a URL like /group/1, but will not match /group/1/a, and throws an error saying, "Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'group/1/a'" despite being a prefix pathMatch.

I's really like to set up a route like this:

```<code>{ path: 'group/:groupId/:path }
</code>```

and have the route 'group/1/a/b/c' resolve the :path parameter to 'a/b/c'.

答:
Simply use wildcards, specifically **:</p>

```<code>path: 'group/:groupId/**', component: GroupComponent,  //...
</code>```

Title: Angular 9 routing anonymous parameters

Body:
I'm working in Angular 9, and trying to capture a route with unknown number of parameters in the URL to express a nested folder structure.

An example group would look like this: /group/:groupId/child1/childofchild1/childofchildofchild1

I don't know how many parameters would follow the :groupId parameter.

Right now, I have a route like this in app.module.ts

RouterModule.forRoot([
      { path: 'group/:groupId', component: GroupComponent, pathMatch: 'prefix' },
]);

This will match a URL like /group/1, but will not match /group/1/a, and throws an error saying, "Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'group/1/a'" despite being a prefix pathMatch.

I's really like to set up a route like this:

{ path: 'group/:groupId/:path }

and have the route 'group/1/a/b/c' resolve the :path parameter to 'a/b/c'.

Body:
Simply use wildcards, specifically **:

path: 'group/:groupId/**', component: GroupComponent,  //...


问:
How to generate one hot encoded data for a set of columns with similar categories
I gathered a bunch of data from the internet to try and predict a sports outcome! But, now I find myself confused on how to prepare the data set for training. Basically, I have a DataFrame that looks as the follows and ofcourse a bunch of many more columns

```<code>            HomeTeam    AwayTeam       HTR   HF      AF  HomePlayStyle  AwayPlayStyle
Date
2014-08-16  Arsenal     Crystal Palace  D   13.0    19.0    4-1-4-1         4-2-3-1
2014-08-16  Leicester   Everton         A   16.0    10.0    4-4-2 double 6  4-2-3-1
2014-08-16  Man United  Swansea         A   14.0    20.0    3-5-2           3-5-2
2014-08-16  QPR         Hull City       D   10.0    10.0    5-3-2           5-4-1
2014-08-16  Stoke City  Aston Villa     D   14.0    9.0     4-2-3-1        4-3-3 Attacking
</code>```

My dependent variable(what I need to predict) would be HTR(3 categories: D-Draw, A-Away wins, H-Home wins). But before training, since I need to prepare the dataset, I believe I need to use one-hot encoding to change the columns [HomeTeam, AwayTeam, HomePlayStyle, AwayPlayStyle] into zeros and ones. However, I have a couple of doubts regarding the approach:

The HomePlayStyle and AwayPlayStyle have similar categories and when I use one hot encoding, the same playstyle(3-5-2, 3rd sample in the example)  is creating two columns but technically they are the same. Would this influence my results? Or should I try to merge them or is there a way to get around this issue? and of course even 4-2-3-1 is present in both columns but pd.get_dummies() creates 2 columns.

With HomeTeam and AwayTeam columns (I have a few temporal stats of these teams in different numerical columns but I believe I need to keep the team names in the dataset during training), am I supposed to one hot encode them? Inspite of creating two columns for the same team(for instance, HomeTeam_Arsenal and AwayTeam_Arsenal), I think there's an advantage here since playing at home is way different than playing away. So this shouldn't be an issue! Am I making the right assumptions? Do I even need to one-hot encode these set of columns?

Any thoughts would be really appreciated.

Edit:
3. How do I make sure my algorithm realizes that HomePlayStyle_4-2-3-1(after getting the dummies) infact represents the HomeTeam and not the AwayTeam? Is there such a thing as connected columns so that I could tell which set of columns belong to HomeTeam and which belong to the AwayTeam.

答:
The theroy part of your question seems more suited fore CrossValidate, so I'll briefly touch that subject. As to one-hot encoding, the easiest way to me is through pandas:

```<code>categorical_cols = ['HomeTeam', 'AwayTeam', 'HomePlayStyle', 'AwayPlayStyle']
X = pd.get_dummies(df, columns=categorical_cols)
</code>```

This will create one column for each possible value in each of those columns with the format {column_name}_{column_value}, so you get columns like HomeTeam_Arsenal.

Problems with variables depend on the kind of models you're thinking of using. Multi-collinearity might be a problem in Logistic Regression, but not as much in, say, Random Forests. Also, never forget that business knowledge is very important, so if you know teams have differing winrates when playing home or away, well, you should include that in your model. If you're not sure, then test both options. Machine learning is a very iterative process, so don't be afraid to try many options.

Body:
I gathered a bunch of data from the internet to try and predict a sports outcome! But, now I find myself confused on how to prepare the data set for training. Basically, I have a DataFrame that looks as the follows and ofcourse a bunch of many more columns

            HomeTeam    AwayTeam       HTR   HF      AF  HomePlayStyle  AwayPlayStyle
Date
2014-08-16  Arsenal     Crystal Palace  D   13.0    19.0    4-1-4-1         4-2-3-1
2014-08-16  Leicester   Everton         A   16.0    10.0    4-4-2 double 6  4-2-3-1
2014-08-16  Man United  Swansea         A   14.0    20.0    3-5-2           3-5-2
2014-08-16  QPR         Hull City       D   10.0    10.0    5-3-2           5-4-1
2014-08-16  Stoke City  Aston Villa     D   14.0    9.0     4-2-3-1        4-3-3 Attacking

My dependent variable(what I need to predict) would be HTR(3 categories: D-Draw, A-Away wins, H-Home wins). But before training, since I need to prepare the dataset, I believe I need to use one-hot encoding to change the columns [HomeTeam, AwayTeam, HomePlayStyle, AwayPlayStyle] into zeros and ones. However, I have a couple of doubts regarding the approach:

The HomePlayStyle and AwayPlayStyle have similar categories and when I use one hot encoding, the same playstyle(3-5-2, 3rd sample in the example)  is creating two columns but technically they are the same. Would this influence my results? Or should I try to merge them or is there a way to get around this issue? and of course even 4-2-3-1 is present in both columns but pd.get_dummies() creates 2 columns.

With HomeTeam and AwayTeam columns (I have a few temporal stats of these teams in different numerical columns but I believe I need to keep the team names in the dataset during training), am I supposed to one hot encode them? Inspite of creating two columns for the same team(for instance, HomeTeam_Arsenal and AwayTeam_Arsenal), I think there's an advantage here since playing at home is way different than playing away. So this shouldn't be an issue! Am I making the right assumptions? Do I even need to one-hot encode these set of columns?

Any thoughts would be really appreciated.

Edit:
3. How do I make sure my algorithm realizes that HomePlayStyle_4-2-3-1(after getting the dummies) infact represents the HomeTeam and not the AwayTeam? Is there such a thing as connected columns so that I could tell which set of columns belong to HomeTeam and which belong to the AwayTeam.

Body:
The theroy part of your question seems more suited fore CrossValidate, so I'll briefly touch that subject. As to one-hot encoding, the easiest way to me is through pandas:

categorical_cols = ['HomeTeam', 'AwayTeam', 'HomePlayStyle', 'AwayPlayStyle']
X = pd.get_dummies(df, columns=categorical_cols)

This will create one column for each possible value in each of those columns with the format {column_name}_{column_value}, so you get columns like HomeTeam_Arsenal.

Problems with variables depend on the kind of models you're thinking of using. Multi-collinearity might be a problem in Logistic Regression, but not as much in, say, Random Forests. Also, never forget that business knowledge is very important, so if you know teams have differing winrates when playing home or away, well, you should include that in your model. If you're not sure, then test both options. Machine learning is a very iterative process, so don't be afraid to try many options.


问:
How do I store repeated inputs in Python? (read description for better understanding, it's really simple)
I want to make a program that could make you input the number of times you want to input something, then ask you for your input. After the amount of times it is over, it prints all of your inputs. I don't know how to word it correctly, but here is an example.

```<code>input:
2
hello 1
hello 2

output:
hello 1
hello 2
</code>```

The first line of input says the number of times I will later input, which is 2 in this case, so I will have to input 2 things before I get the result. After ALL of the inputs are done, it prints my inputs. Can somebody help me on this? Sorry for the bad wording.

答:
Check with this </p>

```<code>a = int (input(" No. of inputs:  "))
c=[]
for x in range (0,a):
    b = input(" Enter Input: ")
    c.append(b)
print (c)
</code>```

Body:
I want to make a program that could make you input the number of times you want to input something, then ask you for your input. After the amount of times it is over, it prints all of your inputs. I don't know how to word it correctly, but here is an example.

input:
2
hello 1
hello 2

output:
hello 1
hello 2

The first line of input says the number of times I will later input, which is 2 in this case, so I will have to input 2 things before I get the result. After ALL of the inputs are done, it prints my inputs. Can somebody help me on this? Sorry for the bad wording.

Body:
Check with this

a = int (input(" No. of inputs:  "))
c=[]
for x in range (0,a):
    b = input(" Enter Input: ")
    c.append(b)
print (c)


问:
Transformer-XL: Input and labels for Language Modeling
I'm trying to finetune the pretrained Transformer-XL model transfo-xl-wt103 for a language modeling task. Therfore, I use the model class TransfoXLLMHeadModel.

To iterate over my dataset I use the LMOrderedIterator from the file tokenization_transfo_xl.py which yields a tensor with the data and its target for each batch (and the sequence length).

Let's assume the following data with batch_size = 1 and bptt = 8:

```<code>data = tensor([[1,2,3,4,5,6,7,8]])
target = tensor([[2,3,4,5,6,7,8,9]])
mems # from the previous output
</code>```

My question is: I currently pass this data into the model like this:

```<code>output = model(input_ids=data, labels=target, mems=mems)
</code>```

Is this correct?

I am wondering because the documentation says for the labels parameter:

labels (:obj:torch.LongTensor of shape :obj:(batch_size, sequence_length), optional, defaults to :obj:None):
              Labels for language modeling.
              Note that the labels are shifted inside the model, i.e. you can set lm_labels = input_ids

So what is it about the parameter lm_labels? I only see labels defined in the forward method.

And when the labels "are shifted" inside the model, does this mean I have to pass data twice (additionally instead of targets) because its shifted inside? But how does the model then know the next token to predict?

I also read through this bug and the fix in this pull request but I don't quite understand how to treat the model now (before vs. after fix)

Thanks in advance for some help!

Edit: Link to issue on Github

答:
That does sound like a typo from another model's convention. You do have to pass data twice, once to input_ids and once to labels (in your case, [1, ... , 8] for both). The model will then attempt to predict [2, ... , 8] from [1, ... , 7]). I am not sure adding something at the beginning of the target tensor would work as that would probably cause size mismatches later down the line.

Passing twice is the default way to do this in transformers; before the aforementioned PR, TransfoXL did not shift labels internally and you had to shift the labels yourself. The PR changed it to be consistent with the library and the documentation, where you have to pass the same data twice.

Body:
I'm trying to finetune the pretrained Transformer-XL model transfo-xl-wt103 for a language modeling task. Therfore, I use the model class TransfoXLLMHeadModel.

To iterate over my dataset I use the LMOrderedIterator from the file tokenization_transfo_xl.py which yields a tensor with the data and its target for each batch (and the sequence length).

Let's assume the following data with batch_size = 1 and bptt = 8:

data = tensor([[1,2,3,4,5,6,7,8]])
target = tensor([[2,3,4,5,6,7,8,9]])
mems # from the previous output

My question is: I currently pass this data into the model like this:

output = model(input_ids=data, labels=target, mems=mems)

Is this correct?

I am wondering because the documentation says for the labels parameter:

labels (:obj:torch.LongTensor of shape :obj:(batch_size, sequence_length), optional, defaults to :obj:None):
              Labels for language modeling.
              Note that the labels are shifted inside the model, i.e. you can set lm_labels = input_ids

So what is it about the parameter lm_labels? I only see labels defined in the forward method.

And when the labels "are shifted" inside the model, does this mean I have to pass data twice (additionally instead of targets) because its shifted inside? But how does the model then know the next token to predict?

I also read through this bug and the fix in this pull request but I don't quite understand how to treat the model now (before vs. after fix)

Thanks in advance for some help!

Edit: Link to issue on Github


问:
Percentile excluding 0 in Google Sheets
Is there a way to ignore 0 in Google Sheets when using:

```<code>=Percentile(A:A,0.9)
</code>```

Like in Excel:

```<code>=PERCENTILE(IF(A1:A18,A1:A18),0.3)
</code>```

But that doesn't seem to work in Google Sheets.

答:
You can use a query formula to exclude 0's

```<code>=PERCENTILE(QUERY(A:A,"where A<>0"), 0.9)</code>```

Functions used:

QUERY

Title: Percentile excluding 0 in Google Sheets

Body:
Is there a way to ignore 0 in Google Sheets when using:

=Percentile(A:A,0.9)

Like in Excel:

=PERCENTILE(IF(A1:A18,A1:A18),0.3)

But that doesn't seem to work in Google Sheets.

Body:
You can use a query formula to exclude 0's

=PERCENTILE(QUERY(A:A,"where A<>0"), 0.9)

Functions used:

QUERY


问:
Google Sheets GS - Sort interval if date (column 1) matches
I have a simple code that auto sorts the 1st column by date (ascending):

```<code>function classificaAuto() {
  var planilha = SpreadsheetApp.getActiveSpreadsheet();
  var folha = planilha.getSheets()[0];
  var intervalo = folha.getRange('A4:H');
  intervalo.sort({column:1, ascending:true});
}
</code>```

Now, I would like to sort (ascending) intervals from B:H that have the same date from column A. How could I do that?

For example, from the sheet below, I would like that it auto-sort B206:H211, then auto-sort B213:H221, and so on.

答:
It sounds like you are looking for multiple level data sorting. You can just include an array of the columns you want to sort by in your sort function, per the Google Apps Script docs:

```<code>intervalo.sort([{column:1, ascending:true}, {column:2, ascending:true}]);
</code>```

Or if they are all ascending, simply:

```<code>intervalo.sort([1, 2]);
</code>```

Body:
I have a simple code that auto sorts the 1st column by date (ascending):

function classificaAuto() {
  var planilha = SpreadsheetApp.getActiveSpreadsheet();
  var folha = planilha.getSheets()[0];
  var intervalo = folha.getRange('A4:H');
  intervalo.sort({column:1, ascending:true});
}

Now, I would like to sort (ascending) intervals from B:H that have the same date from column A. How could I do that?

For example, from the sheet below, I would like that it auto-sort B206:H211, then auto-sort B213:H221, and so on.

Body:
It sounds like you are looking for multiple level data sorting. You can just include an array of the columns you want to sort by in your sort function, per the Google Apps Script docs:

intervalo.sort([{column:1, ascending:true}, {column:2, ascending:true}]);

Or if they are all ascending, simply:

intervalo.sort([1, 2]);


问:
Creating a list from JSON in Flutter
Following an online example I have the following code:

```<code>_fetchData() async {
    setState(() {
      isLoading = true;
    });

    final response = await http.get(
        "https://apiurl...");

    if (response.statusCode == 200) {
      print(json.decode(response.body).runtimeType); // _InternalLinkedHashMap<String, dynamic>

      list = (json.decode(response.body) as List)
          .map((data) => Model.fromJson(data))
          .toList();

      setState(() {
        isLoading = false;
      });
    } else {
      throw Exception('Failed to load');
    }
  }
</code>```

Which returns this error:

```<code>Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
</code>```

This is the response from the API:

```<code>{"results":[{"docid":"123434","title":"A title"}, ...]}
</code>```

Model:

```<code>class Model {
  final String title;
  final String docid;

  Model._({this.title, this.docid});

  factory Model.fromJson(Map<String, dynamic> json) {
    return new Model._(
      title: json['title'],
      docid: json['docid'],
    );
  }
}
</code>```

I understand that the above factory is expecting the argument to be Map<String, dynamic> and the format of the json is different and can be changed, but want to know how to make it work with this format.

*** Edit

Working ListView

```<code>body: Column(
    children: <Widget>[
      Padding(
        padding: EdgeInsets.all(10.0),
        child: TextField(
          onChanged: (value) {
            ...
          },
          controller: _searchController,
          decoration: InputDecoration(

          ...
          ),
        ),
      ),
      Expanded(
        child: SizedBox(
          height: 200.0,
          child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                return Text(list[index].title);
              }),
        ),
      )
    ],
  ),
</code>```

答:
The following was working for me:</p>

```<code>List<Model>.from(
  json.decode(response.body)
  .map((data) => Model.fromJson(data))
)
</code>```

Title: Creating a list from JSON in Flutter

Body:
Following an online example I have the following code:

_fetchData() async {
    setState(() {
      isLoading = true;
    });

    final response = await http.get(
        "https://apiurl...");

    if (response.statusCode == 200) {
      print(json.decode(response.body).runtimeType); // _InternalLinkedHashMap<String, dynamic>

      list = (json.decode(response.body) as List)
          .map((data) => Model.fromJson(data))
          .toList();

      setState(() {
        isLoading = false;
      });
    } else {
      throw Exception('Failed to load');
    }
  }

Which returns this error:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

This is the response from the API:

{"results":[{"docid":"123434","title":"A title"}, ...]}

Model:

class Model {
  final String title;
  final String docid;

  Model._({this.title, this.docid});

  factory Model.fromJson(Map<String, dynamic> json) {
    return new Model._(
      title: json['title'],
      docid: json['docid'],
    );
  }
}

I understand that the above factory is expecting the argument to be Map<String, dynamic> and the format of the json is different and can be changed, but want to know how to make it work with this format.

*** Edit

Working ListView

body: Column(
    children: <Widget>[
      Padding(
        padding: EdgeInsets.all(10.0),
        child: TextField(
          onChanged: (value) {
            ...
          },
          controller: _searchController,
          decoration: InputDecoration(

          ...
          ),
        ),
      ),
      Expanded(
        child: SizedBox(
          height: 200.0,
          child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                return Text(list[index].title);
              }),
        ),
      )
    ],
  ),

Body:
The following was working for me:

List<Model>.from(
  json.decode(response.body)
  .map((data) => Model.fromJson(data))
)


问:
Understanding Eloquent One-to-many Relationships
I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:

A Meeting produces many Documents.

A specific Document can be produced for one Meeting.

Thus a one to many relationship.  I am trying to display the 'meeting_name' in the Document details table but get this error:

Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)

Here is my code.

Please please explain with code solution:

app\Document.php File:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    protected $fillable = [
        'document_name',
        'document_desc',
    ];

    public function meeting(){
        return $this->belongsTo(Meeting::class);
    }
}
</code>```

app\Meeting.php File:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    protected $fillable = [
        'document_id',
        'meeting_name',
        'meeting_desc',
        'room_no',
        'no_of_invitees',
        'comments'
    ];

    public function documents(){
        return $this->hasMany(Document::class);
    }
}
</code>```

app\Http\Controllers\DocumentsController.php File:

```<code>namespace App\Http\Controllers;

use App\Document;
use App\Meeting;
use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index()
    {
        $documents =  Document::all();
        $meetings = Meeting::all();

        return view('documents.index', compact('documents', 'meetings'));
    }
}
</code>```

resources\views\documents\index.blade.php File:

```<code>@foreach($documents as $document)
    <tr>
        <td>{{$document->id}}</td>
        <td>{{$document->document_name}}</td>
        <td>{{$document->document_desc}}</td>
        <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
    </tr>
@endforeach
</code>```

答:
So you have your tables mixed up.

You have a single record per meeting yet you have a document_id in your meetings table which you would need to duplicate meeting record for each document.

Remove the document_id from your meetings table

Add a meeting_id to your documents table

remember to update your models fallible array else you wont get the new columns in the collection.

This should fix your problem as your relationships are correct.

Body:
I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:

A Meeting produces many Documents.

A specific Document can be produced for one Meeting.

Thus a one to many relationship.  I am trying to display the 'meeting_name' in the Document details table but get this error:

Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)

Here is my code.

Please please explain with code solution:

app\Document.php File:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    protected $fillable = [
        'document_name',
        'document_desc',
    ];

    public function meeting(){
        return $this->belongsTo(Meeting::class);
    }
}

app\Meeting.php File:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    protected $fillable = [
        'document_id',
        'meeting_name',
        'meeting_desc',
        'room_no',
        'no_of_invitees',
        'comments'
    ];

    public function documents(){
        return $this->hasMany(Document::class);
    }
}

app\Http\Controllers\DocumentsController.php File:

namespace App\Http\Controllers;

use App\Document;
use App\Meeting;
use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index()
    {
        $documents =  Document::all();
        $meetings = Meeting::all();

        return view('documents.index', compact('documents', 'meetings'));
    }
}

resources\views\documents\index.blade.php File:

@foreach($documents as $document)

        {{$document->id}}
        {{$document->document_name}}
        {{$document->document_desc}}
        {{$document->meetings->meeting_name}}

@endforeach


问:
console.dir - how to show what object it applies to / label it?
Given a declaration like

myobj = {a:1, b:2};

I can write console.dir(myobj).  This results in

```<code>{ a: 1, b: 2 }
</code>```

But say I want to remind myself, in a complex debugging session, what the console.dir is about:

I can write

console.log("myobj"); console.dir(myobj);

This will print

```<code>myobj
{ a: 1, b: 2 }
</code>```

But it's a bit clunky.

Using console.log("myobj:" + myobj);

prints out

```<code>myobj:[object Object]
</code>```

which doesn't work at all.  Is there a better way to label a console.dir?

答:
dir and log take multiple arguments, you are getting that last output because you can't concatenate a string to an object, here is a proper way:

console.log("myobj:", myobj);
```

Use a comma and just pass multiple arguments instead.

Body:
Given a declaration like

myobj = {a:1, b:2};

I can write console.dir(myobj).  This results in

{ a: 1, b: 2 }

But say I want to remind myself, in a complex debugging session, what the console.dir is about:

I can write

console.log("myobj"); console.dir(myobj);

This will print

myobj
{ a: 1, b: 2 }

But it's a bit clunky.

Using console.log("myobj:" + myobj);

prints out

myobj:[object Object]

which doesn't work at all.  Is there a better way to label a console.dir?

Body:
dir and log take multiple arguments, you are getting that last output because you can't concatenate a string to an object, here is a proper way:

console.log("myobj:", myobj);

Use a comma and just pass multiple arguments instead.


问:
best/correct way to add value="" to a <button>
I've been creating buttons in two ways:

```<code><button class="....>NAME</button>
</code>```

and

```<code><div class="btn-group....
     <label class="btn...><input>NAME</input></label>
     <label...
</div>
</code>```

Question is, if I were to add a value to a button (to be manipulated on pressing the button), where /should/ I do that? In the label, the input, or use the < button> method? I'm ignorant, I know.

答:
Only <button> is a real button.

The other is a link styled to look like a button.

Body:
I've been creating buttons in two ways:

<button class="....>NAME</button>

and

<div class="btn-group....
     <input>NAME</input>
     <label...

Question is, if I were to add a value to a button (to be manipulated on pressing the button), where /should/ I do that? In the label, the input, or use the < button> method? I'm ignorant, I know.


问:
Ruby - convert string to date
I have a string like "2011-06-02T23:59:59+05:30".

I want to convert it to date format and need to parse only the date, "2011-06-02".

答:
Simplies way is</p>

```<code>require 'date'
date = "2011-06-02T23:59:59+05:30".gsub(/T.*/, '')
DateTime.parse(date)
</code>```

Title: Ruby - convert string to date

Body:
Simplies way is

require 'date'
date = "2011-06-02T23:59:59+05:30".gsub(/T.*/, '')
DateTime.parse(date)