问:
Unable to use discord.py and quarry at the same time
I am trying to make a discord bot using discord.py that uses the library quarry to interact with a minecraft server.

Unfortunately once I start the discord bot using bot.run() I can't start the reactor for quarry with reactor.run().

I've looked around including aiostream and asyncio but I can't find a solution. I also looked into twisted as quarry uses that.

EDIT: Including current code.

```<code>import asyncio
from twisted.internet import asyncioreactor

asyncioreactor.install(asyncio.get_event_loop())

from quarry.net.client import SpawningClientProtocol, ClientFactory
from quarry.net.auth import Profile
from discord.ext import commands

profile = Profile.from_credentials("email", "password")
bot = commands.Bot(command_prefix=">")

async def start():
    loop = asyncio.get_event_loop()

    loop.create_task(bot.start("token"))

    client = MinecraftBotFactory(profile)

    client.connect("creative.starlegacy.net", 25565)

class MinecraftBotProtocol(SpawningClientProtocol):
    pass

class MinecraftBotFactory(ClientFactory):
    protocol = MinecraftBotProtocol

asyncio.get_event_loop().create_task(start())
asyncio.get_event_loop().run_forever()
</code>```

答:
quarry uses twisted and in order to use it with an asyncio you will need to setup the AsyncioReactor at the start of your application.

import asyncio
from twisted.internet import asyncioreactor
asyncioreactor.install(asyncio.get_event_loop())
```

<p>After that, you should only need to execute <code>bot.start()</code> since <code>quarry</code> relies on the reactor running, and just start the event loop. You cannot <code>await reactor.run()</code> because it's not a coroutine, so just get rid of that function.</p>

<h1>Update: Added example and explanation</h1>

<p>I had a chance to go over <code>discord.py</code> code a bit and found that <code>discord.Client._connect()</code> is basically "blocking code" if you <code>await</code> it, but only if you have another task waits for <code>bot.start()</code> to complete with in the same <code>async def</code>. In other words, it's an infinite poller loop that never returns anything, therefore cannot proceed past the <code>await</code> point. To avoid this you could create a <code>Task</code>. This example "should" work (I haven't tried it on a live server since I don't have a Minecraft client on hand). It starts a server and then when clients try to connect, they get a message saying the Minecraft server is down and then get booted. When a user tries to connect, a Discord message is also sent to the channel.</p>

<pre class="lang-py prettyprint-override"><code>import asyncio
from twisted.internet import asyncioreactor

asyncioreactor.install(asyncio.get_event_loop())

import discord
from quarry.net.server import ServerFactory, ServerProtocol
from twisted.internet import endpoints, reactor

async def start():
    loop = asyncio.get_event_loop()
    minecraft_server = DowntimeFactory()
    minecraft_server_host = "0.0.0.0"
    minecraft_server_port = 25565
    discord_bot_token = "APP_TOKEN"
    discord_channel_id = 0 # CHANNEL ID

    # Start a quarry server
    quarry_server = endpoints.TCP4ServerEndpoint(
        reactor,
        port=minecraft_server_port,
        interface=minecraft_server_host,
    )
    try:
        await quarry_server.listen(minecraft_server).asFuture(loop)
    except Exception as err:
        print(err)
        loop.stop()

    # Start Discord poller
    discord_client = discord.Client(loop=loop)
    loop.create_task(discord_client.start(discord_bot_token))

    @discord_client.event
    async def on_ready():
        """
        After the Discord client connects, set the discord_channel attribute in the
        quarry factory so that server can access Discord functionality.
        """
        discord_channel = discord_client.get_channel(discord_channel_id)
        if discord_channel:
            minecraft_server.discord_channel = discord_channel
            await discord_channel.send("hello world")
        else:
            print("[!] channel no found")
            loop.stop()

class DowntimeProtocol(ServerProtocol):
    def packet_login_start(self, buff):
        buff.discard()
        self.close(self.factory.motd)

        # The Discord channel might not have been set up yet
        if self.factory.discord_channel:
            self.factory.loop.create_task(
                self.factory.discord_channel.send(
                    "Someone is trying to access the Minecraft server!"
                )
            )

class DowntimeFactory(ServerFactory):
    motd = "Down for maintenance"
    loop = asyncio.get_event_loop()
    discord_channel = None
    protocol = DowntimeProtocol

asyncio.get_event_loop().create_task(start())
try:
    asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
    pass
</code>```

Body:
I am trying to make a discord bot using discord.py that uses the library quarry to interact with a minecraft server.

Unfortunately once I start the discord bot using bot.run() I can't start the reactor for quarry with reactor.run().

I've looked around including aiostream and asyncio but I can't find a solution. I also looked into twisted as quarry uses that.

EDIT: Including current code.

import asyncio
from twisted.internet import asyncioreactor

asyncioreactor.install(asyncio.get_event_loop())

from quarry.net.client import SpawningClientProtocol, ClientFactory
from quarry.net.auth import Profile
from discord.ext import commands

profile = Profile.from_credentials("email", "password")
bot = commands.Bot(command_prefix=">")

async def start():
    loop = asyncio.get_event_loop()

    loop.create_task(bot.start("token"))

    client = MinecraftBotFactory(profile)

    client.connect("creative.starlegacy.net", 25565)

class MinecraftBotProtocol(SpawningClientProtocol):
    pass

class MinecraftBotFactory(ClientFactory):
    protocol = MinecraftBotProtocol

asyncio.get_event_loop().create_task(start())
asyncio.get_event_loop().run_forever()

Body:
quarry uses twisted and in order to use it with an asyncio you will need to setup the AsyncioReactor at the start of your application.

import asyncio
from twisted.internet import asyncioreactor
asyncioreactor.install(asyncio.get_event_loop())

After that, you should only need to execute bot.start() since quarry relies on the reactor running, and just start the event loop. You cannot await reactor.run() because it's not a coroutine, so just get rid of that function.

Update: Added example and explanation

I had a chance to go over discord.py code a bit and found that discord.Client._connect() is basically "blocking code" if you await it, but only if you have another task waits for bot.start() to complete with in the same async def. In other words, it's an infinite poller loop that never returns anything, therefore cannot proceed past the await point. To avoid this you could create a Task. This example "should" work (I haven't tried it on a live server since I don't have a Minecraft client on hand). It starts a server and then when clients try to connect, they get a message saying the Minecraft server is down and then get booted. When a user tries to connect, a Discord message is also sent to the channel.

import asyncio
from twisted.internet import asyncioreactor

asyncioreactor.install(asyncio.get_event_loop())

import discord
from quarry.net.server import ServerFactory, ServerProtocol
from twisted.internet import endpoints, reactor

async def start():
    loop = asyncio.get_event_loop()
    minecraft_server = DowntimeFactory()
    minecraft_server_host = "0.0.0.0"
    minecraft_server_port = 25565
    discord_bot_token = "APP_TOKEN"
    discord_channel_id = 0 # CHANNEL ID

    # Start a quarry server
    quarry_server = endpoints.TCP4ServerEndpoint(
        reactor,
        port=minecraft_server_port,
        interface=minecraft_server_host,
    )
    try:
        await quarry_server.listen(minecraft_server).asFuture(loop)
    except Exception as err:
        print(err)
        loop.stop()

    # Start Discord poller
    discord_client = discord.Client(loop=loop)
    loop.create_task(discord_client.start(discord_bot_token))

    @discord_client.event
    async def on_ready():
        """
        After the Discord client connects, set the discord_channel attribute in the
        quarry factory so that server can access Discord functionality.
        """
        discord_channel = discord_client.get_channel(discord_channel_id)
        if discord_channel:
            minecraft_server.discord_channel = discord_channel
            await discord_channel.send("hello world")
        else:
            print("[!] channel no found")
            loop.stop()

class DowntimeProtocol(ServerProtocol):
    def packet_login_start(self, buff):
        buff.discard()
        self.close(self.factory.motd)

        # The Discord channel might not have been set up yet
        if self.factory.discord_channel:
            self.factory.loop.create_task(
                self.factory.discord_channel.send(
                    "Someone is trying to access the Minecraft server!"
                )
            )

class DowntimeFactory(ServerFactory):
    motd = "Down for maintenance"
    loop = asyncio.get_event_loop()
    discord_channel = None
    protocol = DowntimeProtocol

asyncio.get_event_loop().create_task(start())
try:
    asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
    pass


来源: stackexchange

问:
What does \0 mean in sed?
I have the following code:

```<code>echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/\1/p"
</code>```

It prints 12 as expected, since \1 refers to the first capturing group.

However, if \0 is used instead of \1, the output is 12. Chapter Name, the entire input string is printed.

It seems that as long as the regex found a match, \0 prints the entire input string. Is this correct?

I'm running Debian 10.2.

答:
The \0 is a placeholder for the whole match value.

Note that capturing group indices start with 1 and go up until 9 in POSIX regex patterns. The zeroth group is the whole match.

Also, instead of \0, it is more common - and probably more portable - to use & in sed.

```<code>echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/\0/p"
</code>```

is equal to

```<code>echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/&/p"
</code>```

You may read more about & at Using & as the matched string.

ContentLicense: CC BY-SA 4.0

Title: What does \0 mean in sed?

Body:
I have the following code:

echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/\1/p"

It prints 12 as expected, since \1 refers to the first capturing group.

However, if \0 is used instead of \1, the output is 12. Chapter Name, the entire input string is printed.

It seems that as long as the regex found a match, \0 prints the entire input string. Is this correct?

I'm running Debian 10.2.

Body:
The \0 is a placeholder for the whole match value.

Note that capturing group indices start with 1 and go up until 9 in POSIX regex patterns. The zeroth group is the whole match.

Also, instead of \0, it is more common - and probably more portable - to use & in sed.

echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/\0/p"

is equal to

echo "12. Chapter Name" | sed -n -E "s/([0-9]{2})\.[[:space:]].*/&/p"

You may read more about & at Using & as the matched string.


问:
How to properly pattern match JsonConversions
Hi I have the following code which works as I expect but the compiler warns me about incomplete pattern matching when I pattern match in the Option.defaultWith function. Is there a smarter way to achieve the same effect but without warnings?

I have been thinking about throwing an exception for the rest of the cases but that's pretty ugly.

```<code>namespace JsonParser

open System
open System.Globalization
open FSharp.Data
open FSharp.Data.Runtime

type public Key = string

type public Value =
    | Int of int
    | Double of double
    | Decimal of decimal
    | String of string
    | DateTime of DateTime
    | Boolean of Boolean
    | Array of Value []
    | Guid of Guid
    | Null
    | Object of Record []

and public Record =
    { Key: Key
      Value: Value }

module public Json =

    let private culture = CultureInfo.InvariantCulture
    let private emptyArray = Array.empty<String>

    let rec private map (value: JsonValue) =
        JsonConversions.AsInteger culture value
        |> Option.map Value.Int
        |> Option.orElseWith (fun () -> JsonConversions.AsDecimal culture value |> Option.map Value.Decimal)
        |> Option.orElseWith (fun () -> JsonConversions.AsFloat emptyArray true culture value |> Option.map Decimal |> Option.map Value.Decimal)
        |> Option.orElseWith (fun () -> JsonConversions.AsGuid value |> Option.map Value.Guid)
        |> Option.orElseWith (fun () -> JsonConversions.AsDateTime culture value |> Option.map Value.DateTime)
        |> Option.orElseWith (fun () -> JsonConversions.AsBoolean value |> Option.map Value.Boolean)
        |> Option.defaultWith (fun () ->
            match value with
            | JsonValue.String x -> Value.String x
            | JsonValue.Null -> Value.Null
            | JsonValue.Array x ->
                x
                |> Array.map map
                |> Value.Array
            | JsonValue.Record x ->
                x
                |> Array.map (fun (x, y) ->
                    { Key = x
                      Value = map y })
                |> Value.Object)
</code>```

答:
The answer really depends on how you want to handle various corner cases in your JSON data.

The operations in JsonConversions are implemented in a way where they attempt to convert the value to the target type whenever this can reasonably be done. This means that using those, a value true, 1 and "yes" will all be converted to boolan true. Is this what you want? If so, then I would probably just add a case to the pattern match that throws an exception, saying that the situation should not happen:

```<code>match value with
| JsonValue.String x -> Value.String x
| JsonValue.Null -> Value.Null
| JsonValue.Array x -> (...)
| JsonValue.Record x -> (...)
| JsonValue.Float _ | JsonValue.Number _ | JsonValue.Boolean _ ->
    failwith "should never happen: Numbers and booleans handled earlier!"
</code>```

If you want to turn JSON value "yes" to  Value.String("yes") rather than to Value.Boolean(true), then it is a lot easier if you directly pattern match on JsonValue:

```<code>let rec private map (value: JsonValue) =
    match value with
    | JsonValue.Float f -> Value.Double f
    | JsonValue.Number n -> Value.Decimal n
    | JsonValue.Boolean b -> Value.Boolean b
    | JsonValue.String x -> Value.String x
    | JsonValue.Null -> Value.Null
    | JsonValue.Array x ->
        x |> Array.map map |> Value.Array
    | JsonValue.Record x ->
        x |> Array.map (fun (x, y) -> { Key = x; Value = map y }) |> Value.Object
</code>```

You can find the details about how JsonConversions work by looking at the relevant file in the source code: JsonConversions and TextConversions.

Body:
Hi I have the following code which works as I expect but the compiler warns me about incomplete pattern matching when I pattern match in the Option.defaultWith function. Is there a smarter way to achieve the same effect but without warnings?

I have been thinking about throwing an exception for the rest of the cases but that's pretty ugly.

namespace JsonParser

open System
open System.Globalization
open FSharp.Data
open FSharp.Data.Runtime

type public Key = string

type public Value =
    | Int of int
    | Double of double
    | Decimal of decimal
    | String of string
    | DateTime of DateTime
    | Boolean of Boolean
    | Array of Value []
    | Guid of Guid
    | Null
    | Object of Record []

and public Record =
    { Key: Key
      Value: Value }

module public Json =

    let private culture = CultureInfo.InvariantCulture
    let private emptyArray = Array.empty<String>

    let rec private map (value: JsonValue) =
        JsonConversions.AsInteger culture value
        |> Option.map Value.Int
        |> Option.orElseWith (fun () -> JsonConversions.AsDecimal culture value |> Option.map Value.Decimal)
        |> Option.orElseWith (fun () -> JsonConversions.AsFloat emptyArray true culture value |> Option.map Decimal |> Option.map Value.Decimal)
        |> Option.orElseWith (fun () -> JsonConversions.AsGuid value |> Option.map Value.Guid)
        |> Option.orElseWith (fun () -> JsonConversions.AsDateTime culture value |> Option.map Value.DateTime)
        |> Option.orElseWith (fun () -> JsonConversions.AsBoolean value |> Option.map Value.Boolean)
        |> Option.defaultWith (fun () ->
            match value with
            | JsonValue.String x -> Value.String x
            | JsonValue.Null -> Value.Null
            | JsonValue.Array x ->
                x
                |> Array.map map
                |> Value.Array
            | JsonValue.Record x ->
                x
                |> Array.map (fun (x, y) ->
                    { Key = x
                      Value = map y })
                |> Value.Object)

Body:
The answer really depends on how you want to handle various corner cases in your JSON data.

The operations in JsonConversions are implemented in a way where they attempt to convert the value to the target type whenever this can reasonably be done. This means that using those, a value true, 1 and "yes" will all be converted to boolan true. Is this what you want? If so, then I would probably just add a case to the pattern match that throws an exception, saying that the situation should not happen:

match value with
| JsonValue.String x -> Value.String x
| JsonValue.Null -> Value.Null
| JsonValue.Array x -> (...)
| JsonValue.Record x -> (...)
| JsonValue.Float _ | JsonValue.Number _ | JsonValue.Boolean _ ->
    failwith "should never happen: Numbers and booleans handled earlier!"

If you want to turn JSON value "yes" to  Value.String("yes") rather than to Value.Boolean(true), then it is a lot easier if you directly pattern match on JsonValue:

let rec private map (value: JsonValue) =
    match value with
    | JsonValue.Float f -> Value.Double f
    | JsonValue.Number n -> Value.Decimal n
    | JsonValue.Boolean b -> Value.Boolean b
    | JsonValue.String x -> Value.String x
    | JsonValue.Null -> Value.Null
    | JsonValue.Array x ->
        x |> Array.map map |> Value.Array
    | JsonValue.Record x ->
        x |> Array.map (fun (x, y) -> { Key = x; Value = map y }) |> Value.Object

You can find the details about how JsonConversions work by looking at the relevant file in the source code: JsonConversions and TextConversions.


问:
How to attach div to cursor each time window scrolls
I've just started programming a few months ago and I am very new to the language.
I wanted to make a custom cursor and I found this code that works perfectly. The only problem is that when scrolling the Custom cursor sticks to de background and scrolls with the body. It doesn't look natural as it should stick in place. What am i missing here?
Thanks

```<code>$( document ).ready(function() {

    //attach div to cursor each time mouse moves
    $(document).mousemove(function(e){
        $(".custom-cursor").css({left:e.pageX, top:e.pageY});
    });

    //attempt to attach div to cursor each time window scrolls

    $(document).on('scroll', function(e){
           $(".custom-cursor").css({left:e.pageX, top:e.pageY});
    });

//change cursor over menu
$('body a').mouseleave(function() {
    $('.custom-cursor').removeClass('activemenu');
});
</code>```

});

答:
Setting your cursor div to position: fixed should do the trick.

EDIT:
As another user commented, cursor: url(custom.cur),auto; is the better solution obviously.  You're doing a lot of unnecessary js operations otherwise.

Body:
I've just started programming a few months ago and I am very new to the language.
I wanted to make a custom cursor and I found this code that works perfectly. The only problem is that when scrolling the Custom cursor sticks to de background and scrolls with the body. It doesn't look natural as it should stick in place. What am i missing here?
Thanks

$( document ).ready(function() {

    //attach div to cursor each time mouse moves
    $(document).mousemove(function(e){
        $(".custom-cursor").css({left:e.pageX, top:e.pageY});
    });

    //attempt to attach div to cursor each time window scrolls

    $(document).on('scroll', function(e){
           $(".custom-cursor").css({left:e.pageX, top:e.pageY});
    });

//change cursor over menu
$('body a').mouseleave(function() {
    $('.custom-cursor').removeClass('activemenu');
});

});


问:
How can I compare numbers from a list only with the next number (neighbor)?
All I want to do is to compare the first number from a list with the second number from the same list, the second one with the third one, and so on.

input:

```<code>lst = [1,2,3,2,1]
</code>```

output:

```<code>result = ["Lower", "Lower", "Higher", "Higher"]
</code>```

(1 is lower than 2, 2 is lower than 3, 3 is higher than 2, 2 is higher than 1)

It's kinda ugly (a list comprehension would be great), but my approach for that would be:

```<code>lst = [1,2,3,2,1]
result = []
x = 0

try:
    for i in range(len(lst)):
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
except IndexError:
    print(result)
    print("Out of range")
</code>```

答:
Since your strings higher and lower are basically proxies for boolean greater/less than, you can make this pretty clean with:

```<code>lst = [1,2,3,2,1]

vals = ['higher', 'lower']

[vals[m < n] for m, n in zip(lst, lst[1:])]
# ['lower', 'lower', 'higher', 'higher']
</code>```

Body:
All I want to do is to compare the first number from a list with the second number from the same list, the second one with the third one, and so on.

input:

lst = [1,2,3,2,1]

output:

result = ["Lower", "Lower", "Higher", "Higher"]

(1 is lower than 2, 2 is lower than 3, 3 is higher than 2, 2 is higher than 1)

It's kinda ugly (a list comprehension would be great), but my approach for that would be:

lst = [1,2,3,2,1]
result = []
x = 0

try:
    for i in range(len(lst)):
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
except IndexError:
    print(result)
    print("Out of range")

Body:
Since your strings higher and lower are basically proxies for boolean greater/less than, you can make this pretty clean with:

lst = [1,2,3,2,1]

vals = ['higher', 'lower']

[vals[m < n] for m, n in zip(lst, lst[1:])]
# ['lower', 'lower', 'higher', 'higher']


问:
Replace null with known value with same id
How can I do that in a optimal way?

TABLE

```<code>ID FLAG VALUE
----------------------------
1   Y   52
1   N   NULL
2   Y   51
3   N   54
</code>```

OUTPUT

```<code>ID FLAG VALUE
----------------------------
1   Y   52
1   N   52
2   Y   51
3   N   54
</code>```

答:
```<code>UPDATE
  theTable
SET
  value = (SELECT MAX(value) FROM theTable i WHERE i.id = theTable.id)
WHERE
  value IS NULL
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I do that in a optimal way?

TABLE

ID FLAG VALUE
----------------------------
1   Y   52
1   N   NULL
2   Y   51
3   N   54

OUTPUT

ID FLAG VALUE
----------------------------
1   Y   52
1   N   52
2   Y   51
3   N   54


问:
I'm trying to get alt text of an image to appear in a paragraph with event listeners
```<code>var imgHover = document.getElementById("theImg");
imgHover.addEventListener('click', altText(imgHover));

function altText(theText)
{
  document.getElementById("alt-text").innerHTML = theText;
}
</code>```

What do I use to refer to an image's alt text through a function?

It gives an error: cannot set property 'innerHTML' of null

```<code><img src="frozen-kingscreek.jpg" alt="This is nice creek" id="theImg">
<img src="hungry-ravens.jpg" alt="This is nice bird" id="theImg">
<img src="snapping-turtle.jpg" alt="This is nice turtle" id="theImg">

<p id="no"></p>

<script src="script.js"></script>
</code>```

this is my index file

答:
To get an attribute of an HTML element use getAttribute

```<code>element.getAttribute(attributename)
</code>```

Ideally id should be unique, however in your case all img tag has same id.

```<code>var imgHover = document.getElementById("theImg");
imgHover.addEventListener('click', altText);

function altText()
{
  document.getElementById("alt-text").innerHTML = this.getAttribute("alt");
}
</code>```

To add click event to all the images which have css class .example

```<code>document.querySelectorAll(".example").forEach(img => {
 img.addEventListener('click', () => {
   document.getElementById("alt-text").innerHTML = img.getAttribute("alt");
 });
});
</code>```

Body:
var imgHover = document.getElementById("theImg");
imgHover.addEventListener('click', altText(imgHover));

function altText(theText)
{
  document.getElementById("alt-text").innerHTML = theText;
}

What do I use to refer to an image's alt text through a function?

It gives an error: cannot set property 'innerHTML' of null

this is my index file

Body:
To get an attribute of an HTML element use getAttribute

element.getAttribute(attributename)

Ideally id should be unique, however in your case all img tag has same id.

var imgHover = document.getElementById("theImg");
imgHover.addEventListener('click', altText);

function altText()
{
  document.getElementById("alt-text").innerHTML = this.getAttribute("alt");
}

To add click event to all the images which have css class .example

document.querySelectorAll(".example").forEach(img => {
 img.addEventListener('click', () => {
   document.getElementById("alt-text").innerHTML = img.getAttribute("alt");
 });
});


问:
Can't find url views when deploying spring boot on WebSphere
I'm starting a simple project in spring boot, right now I just want to show a startup view, but when deploying on a WebSphere 9 server, it appears when I start "Error 404: SRVE0190E: File not Found: /"
and if I put the url of another controller method for example /login
the same error comes out
"Error 404: java.io.FileNotFoundException: SRVE0190E: File not Found: /login"
This is my controller

```<code>@Controller
public class HomeController {

    @RequestMapping(value="/", method = RequestMethod.GET)
      public String home() {
        return "example";
    }

    @RequestMapping(value="/login", method=RequestMethod.GET)
    public String login() {
        return "example.html";

    }
}
</code>```

Create the explame.html in several places of the project to know if spring recognized it in any of them, but I always got the same message, I leave an image of the initial project structure and my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.BUILD-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.com.ioks</groupId>
    <artifactId>ExampleFirst</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ExampleFirst</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

structure project

UPDATE

I was able to visualize my start view with  / and / login, as I indicated in my controller, it was as @Jalil.Jarjanazy told me in his answer, I put the html file in templates, but not in templates of the empty package that is in src , because when I want to add something there, it shows me the message: "Files created outside of a web content folder will not be included in your deployed Web application.
", I added it in WEB-INF / classes / templates, another very strange thing is that in Eclipse it does not show me the classes folder, but it is in the project, I manually put the html file and ran the project, I think this is not is the proper way to do it, could you tell me what I'm doing wrong, why can't I see the folder classes in eclipse?

答:
Your example.html file should be in the templates folder.

And you should only return the only name of the html file (example) in your controller, so no need for the .html.

Body:
I'm starting a simple project in spring boot, right now I just want to show a startup view, but when deploying on a WebSphere 9 server, it appears when I start "Error 404: SRVE0190E: File not Found: /"
and if I put the url of another controller method for example /login
the same error comes out
"Error 404: java.io.FileNotFoundException: SRVE0190E: File not Found: /login"
This is my controller

@Controller
public class HomeController {

    @RequestMapping(value="/", method = RequestMethod.GET)
      public String home() {
        return "example";
    }

    @RequestMapping(value="/login", method=RequestMethod.GET)
    public String login() {
        return "example.html";

    }
}

Create the explame.html in several places of the project to know if spring recognized it in any of them, but I always got the same message, I leave an image of the initial project structure and my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.BUILD-SNAPSHOT</version>
        <relativePath/>
    </parent>
    <groupId>org.com.ioks</groupId>
    <artifactId>ExampleFirst</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ExampleFirst</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

structure project

UPDATE

I was able to visualize my start view with  / and / login, as I indicated in my controller, it was as @Jalil.Jarjanazy told me in his answer, I put the html file in templates, but not in templates of the empty package that is in src , because when I want to add something there, it shows me the message: "Files created outside of a web content folder will not be included in your deployed Web application.
", I added it in WEB-INF / classes / templates, another very strange thing is that in Eclipse it does not show me the classes folder, but it is in the project, I manually put the html file and ran the project, I think this is not is the proper way to do it, could you tell me what I'm doing wrong, why can't I see the folder classes in eclipse?


问:
Is it possible to define variables in a task for a role?
I need to include a role in my own role, which relies on variables being set. Can I include them in a task and will they be applied to that included role?

Something like this:

```<code>- name: Configure firewall ports
  include_role:
    name: ipr-cnrs.nftables
  vars:
    - nft_define:
        input tcp accepted:
          name: in_tcp_accept
          value: '{ 22, 23 }'
</code>```

答:
You can pass a variable with include_role as shown below according to the documentation:

```<code>- name: Pass variables to role
  include_role:
    name: myrole
  vars:
    rolevar1: value from task
</code>```

So your example above can use vars with include_role.

Body:
I need to include a role in my own role, which relies on variables being set. Can I include them in a task and will they be applied to that included role?

Something like this:

- name: Configure firewall ports
  include_role:
    name: ipr-cnrs.nftables
  vars:
    - nft_define:
        input tcp accepted:
          name: in_tcp_accept
          value: '{ 22, 23 }'

Body:
You can pass a variable with include_role as shown below according to the documentation:

- name: Pass variables to role
  include_role:
    name: myrole
  vars:
    rolevar1: value from task

So your example above can use vars with include_role.


问:
scrollToPosition() when updating RecyclerView in a fragment
I've made a list which gets items from a Room-database using LiveData. This liveData<List> is then bound to a recyclerView, using a BindingAdapter.
The lists adapter is  listAdapter, not `RecyclerView.Adapter.

I need help holding onto the scroll-state or somehow returning to the scroll-index I was at before the recyclerView reloaded:

```<code>//In ViewModel
    val movieList = moviesRepository.movies
</code>```

..

```<code>//in Repo
  val movies: LiveData<List<Movie>> =
    Transformations.map(database.movieDao.getMovies()) {
        it.asDomainModel()
    }
</code>```

Every time the DB updates, the recyclerView shoots back up to the top.

And here's the bindingAdapter for the RecyclerView and the list.

```<code>@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<Movie>?) {
    val adapter = recyclerView.adapter as MovieListAdapter
    //Log.d("listData binding", "${data}")
    adapter.submitList(data)
}
</code>```

I think I need to  use something like recyclerView.smoothScrollToPosition(la.getItemCount());
after the update has occured, but I don't know how to automatically call it when the update has occured

Project Repo

答:
First of all don't use ListAdapter RecyclerView has a more optimized adapter here

in your adapter provide a function that overrides the item list and there is where you notify the data change

Use smoothScrollToPosition(lastVisiblePosition) to scroll to the last visible position where lastVisiblePosition = layoutManager.findFirstVisibleItemPosition()

Update lastVisiblePosition before you push new items to the adapter notifyDatasetChanged()

Step 2

```<code>fun updateList(newItems:List<Movie>) {
    moviesList.addAll(newItems)
    lastVisiblePosition = layoutManager.findFirstVisibleItemPosition()
    notifyDataSetChanged()
}
</code>```

from your view when you call adapter.updateList(newItems) just call recyclerView.smoothScrollToPosition(adapter.lastVisiblePosition)

Body:
I've made a list which gets items from a Room-database using LiveData. This liveData<List> is then bound to a recyclerView, using a BindingAdapter.
The lists adapter is  listAdapter, not `RecyclerView.Adapter.

I need help holding onto the scroll-state or somehow returning to the scroll-index I was at before the recyclerView reloaded:

//In ViewModel
    val movieList = moviesRepository.movies

..

//in Repo
  val movies: LiveData<List<Movie>> =
    Transformations.map(database.movieDao.getMovies()) {
        it.asDomainModel()
    }

Every time the DB updates, the recyclerView shoots back up to the top.

And here's the bindingAdapter for the RecyclerView and the list.

@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<Movie>?) {
    val adapter = recyclerView.adapter as MovieListAdapter
    //Log.d("listData binding", "${data}")
    adapter.submitList(data)
}

I think I need to  use something like recyclerView.smoothScrollToPosition(la.getItemCount());
after the update has occured, but I don't know how to automatically call it when the update has occured

Project Repo

Body:
First of all don't use ListAdapter RecyclerView has a more optimized adapter here

in your adapter provide a function that overrides the item list and there is where you notify the data change

Use smoothScrollToPosition(lastVisiblePosition) to scroll to the last visible position where lastVisiblePosition = layoutManager.findFirstVisibleItemPosition()

Update lastVisiblePosition before you push new items to the adapter notifyDatasetChanged()

Step 2

fun updateList(newItems:List<Movie>) {
    moviesList.addAll(newItems)
    lastVisiblePosition = layoutManager.findFirstVisibleItemPosition()
    notifyDataSetChanged()
}

from your view when you call adapter.updateList(newItems) just call recyclerView.smoothScrollToPosition(adapter.lastVisiblePosition)


问:
Adding a search feature in a discord.py music bot
This is my code for playing music using a discord bot but i have to manually enter the url and i can't figure out a way to add a search feature.

To play the music i am downloading the audio in the url and playing the audio using ffmpeg.
If you don't understand something i'm happy to answer.

```<code>@client.command(pass_context=True)
async def play(ctx, url: str):

    def check_queue():
        Queue_infile = os.path.isdir("./Queue")
        if Queue_infile is True:
            DIR = os.path.abspath(os.path.realpath("Queue"))
            length = len(os.listdir(DIR))
            still_q = length - 1
            try:
                first_file = os.listdir(DIR)[0]
            except:
                print("No more queued song(s)\n")
                queues.clear()
                return
            main_location = os.path.dirname(os.path.realpath(__file__))
            song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
            if length != 0:
                print("Song done, playing next queued\n")
                print(f"Songs still in queue: {still_q}")
                song_there = os.path.isfile("song.mp3")
                if song_there:
                    os.remove("song.mp3")
                shutil.move(song_path, main_location)
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, 'song.mp3')

                voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
                voice.source = discord.PCMVolumeTransformer(voice.source)
                voice.source.volume = 0.2

            else:
                queues.clear()
                return

        else:
            queues.clear()
            print("No songs were queued before the ending of the last song\n")

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            queues.clear()
            print("Removed old song file")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        return

    Queue_infile = os.path.isdir("./Queue")
    try:
        Queue_folder = "./Queue"
        if Queue_infile is True:
            print("Removed old Queue Folder")
            shutil.rmtree(Queue_folder)
    except:
        print("No old Queue folder")

    voice = get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])
    except:
        c_path = os.path.dirname(os.path.realpath(__file__))
        system("spotdl -f " + '"' + c_path + '"' + " -s " + url)

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed File: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.07

    nname = name.rsplit("-", 2)
    await ctx.send(f"Playing: {nname[0]}")
    print("playing\n")
</code>```

ignore the following text:
erviervwuivvbutrjbbrgbiuoj24piofi;kdl,vv4j48v02i4oi;blk;'vdklcvefvijnvkwfjv,mwri3efjkdvdfvfhbvuvriurfuivfubvjfvlkjdfvfjvkflvkjdfvdfljvwrjkgvlgrvhjwrvkjwrgvkrjhbhjrvhiurvrvjkfjv

答:
Use Youtube API's Search function to search on Youtube. It also returns video ID, which can you transform into a link then. Make another python file for that, though.
Hope this helped</p>

Body:
This is my code for playing music using a discord bot but i have to manually enter the url and i can't figure out a way to add a search feature.

To play the music i am downloading the audio in the url and playing the audio using ffmpeg.
If you don't understand something i'm happy to answer.

@client.command(pass_context=True)
async def play(ctx, url: str):

    def check_queue():
        Queue_infile = os.path.isdir("./Queue")
        if Queue_infile is True:
            DIR = os.path.abspath(os.path.realpath("Queue"))
            length = len(os.listdir(DIR))
            still_q = length - 1
            try:
                first_file = os.listdir(DIR)[0]
            except:
                print("No more queued song(s)\n")
                queues.clear()
                return
            main_location = os.path.dirname(os.path.realpath(__file__))
            song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
            if length != 0:
                print("Song done, playing next queued\n")
                print(f"Songs still in queue: {still_q}")
                song_there = os.path.isfile("song.mp3")
                if song_there:
                    os.remove("song.mp3")
                shutil.move(song_path, main_location)
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, 'song.mp3')

                voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
                voice.source = discord.PCMVolumeTransformer(voice.source)
                voice.source.volume = 0.2

            else:
                queues.clear()
                return

        else:
            queues.clear()
            print("No songs were queued before the ending of the last song\n")

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            queues.clear()
            print("Removed old song file")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        return

    Queue_infile = os.path.isdir("./Queue")
    try:
        Queue_folder = "./Queue"
        if Queue_infile is True:
            print("Removed old Queue Folder")
            shutil.rmtree(Queue_folder)
    except:
        print("No old Queue folder")

    voice = get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])
    except:
        c_path = os.path.dirname(os.path.realpath(__file__))
        system("spotdl -f " + '"' + c_path + '"' + " -s " + url)

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed File: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.07

    nname = name.rsplit("-", 2)
    await ctx.send(f"Playing: {nname[0]}")
    print("playing\n")

ignore the following text:
erviervwuivvbutrjbbrgbiuoj24piofi;kdl,vv4j48v02i4oi;blk;'vdklcvefvijnvkwfjv,mwri3efjkdvdfvfhbvuvriurfuivfubvjfvlkjdfvfjvkflvkjdfvdfljvwrjkgvlgrvhjwrvkjwrgvkrjhbhjrvhiurvrvjkfjv


问:
ERROR Android emulator gets killed in Android Studio
After updating to Android Studio 2 when I try to run my application and choose an emulator, I wait for the emulator to start and it suddenly gets killed. I can see the emulator process for some minutes but never the GUI. In Android studio, I get the error

```<code>android studio Error while waiting for the device: The emulator process for AVD was killed
</code>```

This happens even if I run the emulator outside Android Studio. I have tried both an Android 6 and an Android 4.4-based emulator.
Running on a Windows 7 x64 PC. Similar post to another StackOverflow post which was closed. I have tried various ram, VM heap, and resolution settings.

答:
I had the same issue, the problem was there is not enough space in my disk drive.. you can see details about your specific situation in layer 'Event Log' this layer regularly is at the bottom on Android studio, it was my output Log:

"02:45 PM   Emulator: emulator: ERROR: Not enough space to create userdata partition. Available: 3310.363281 MB at /home/user/.android/avd/my_Nexus_5X_API_27.avd, need 7372.800000 MB."

I had just 7 GB free, so just delete some GB's in my D.D. and it's working fine.

Body:
After updating to Android Studio 2 when I try to run my application and choose an emulator, I wait for the emulator to start and it suddenly gets killed. I can see the emulator process for some minutes but never the GUI. In Android studio, I get the error

android studio Error while waiting for the device: The emulator process for AVD was killed

This happens even if I run the emulator outside Android Studio. I have tried both an Android 6 and an Android 4.4-based emulator.
Running on a Windows 7 x64 PC. Similar post to another StackOverflow post which was closed. I have tried various ram, VM heap, and resolution settings.


问:
When creating a HTML Table in an Email, how can add space above one row, but not above all of them?
When creating a HTML table in an Email, how can add space above one row, but not above all of them?

Example: I have a table that is two columns wide. Part way down the table I am inserting a 'sub header' of sorts by having one cell merge the two columns. Above this row, I want to have more space, but I don't want to apply this above all rows, like css would commonly do.

Any suggestions?

答:
Your code should be inline anyway, because many email clients do not read embedded styles (the code within ).

I.e., as @David said in comments,

```<code><table>
  <tr>
    <td>...
    </td>
    <td>...
    </td>
  </tr>
  <tr>
    <td style="padding-top:30px">Sub-header
    </td>
  </tr>
</table>
</code>```

You can't use margin as Outlook desktops don't allow it.

An alternative that might suit you is a faux-table row, with a non-breaking space set at a specific height (both parameters there are necessary for cross-email-compatibility):

```<code><tr>
  <td style="font-size:30px;line-height:30px;">
  </td>
</tr>
</code>```

Body:
Your code should be inline anyway, because many email clients do not read embedded styles (the code within <style>...</style>).

I.e., as @David said in comments,

<table>
  <tr>
    <td>...
    </td>
    <td>...
    </td>
  </tr>
  <tr>
    <td style="padding-top:30px">Sub-header
    </td>
  </tr>
</table>

You can't use margin as Outlook desktops don't allow it.

An alternative that might suit you is a faux-table row, with a non-breaking space set at a specific height (both parameters there are necessary for cross-email-compatibility):

<tr>
  <td style="font-size:30px;line-height:30px;">&nbsp;
  </td>
</tr>


问:
NULL pointer with boost::shared_ptr?
What's the equivalent to the following:

```<code>std::vector<Foo*> vec;
vec.push_back(NULL);
</code>```

when dealing with boost::shared_ptr? Is it the following code?

```<code>std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());
</code>```

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

```<code>boost::shared_ptr<Foo> nullPtr;
</code>```

答: Yes, declare a global static null pointer.</p>

OwnerDisplayName: Frank

ContentLicense: CC BY-SA 2.5

Title: NULL pointer with boost::shared_ptr?

Body:
What's the equivalent to the following:

std::vector<Foo*> vec;
vec.push_back(NULL);

when dealing with boost::shared_ptr? Is it the following code?

std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

boost::shared_ptr<Foo> nullPtr;

OwnerDisplayName: Infamous Cow


问:
A website sells three types of components. What's a good way to make an interactive component compatability checker for visitors?
A company sells a variety of component As, a variety of component Bs and a variety of component Cs (for example CPUs, motherboards and RAM).  They want some kind of web app that allows a visitor to select A3000, B64 and C24, and see if that combination will is compatible.

Their website is built in Joomla.

What would be a good way to go about creating something like this?

The two thoughts I have currently is a searchable database like this: http://processormatch.intel.com/CompDB/

Or something like the 'post new ad' on Gumtree where selecting the first category opens up the second list of compatible pieces, and then a third:
http://www.gumtree.com/add_posting.html

I don't have much database experience, so the simpler the solution the better.

Thanks for any thoughts!

答:
For computer hardware there are some solutions available as plugin for oscommerce and descendants (aka dedicated e-commerce software). But their use is quite limited since the logic for this kind of solution is usualy quite complex.

Its mostly not select everything and then ... but select one and only the compatible selections are left or a more wizard like approach which step by step leads you through the process of creating a custom product.

Furthermore Joomla is not an ecommerce solution, Virtuemart would be, but then again its "only" a shopping cart extension.
Try googling "osCommerce Product Customization Module (PC Configurator)" or variations of that to get an idea what kind of solution is available. The first step should be selecting your ecommerce system.

The most common solution for me is to program a custom wizard and and in the last step e.g. just insert everything into the shopping cart of a standard ecommerce solution.

FYI : Custom products in Drupal or OSCommerce?


问:
Gallery grid not displaying properly
I've run into a problem with the Wordpress theme I'm using. I'm not a dev by any means so please bear with me, I'll try my best to describe the issue as clear as possible.

Basically the grid gallery won't display until I change the size of the browser's window. Upon loading the page, the element seems to be there but images are not visible. They pop into their places right after I make any change to the browser's windows size. Then everything works as intended until you reload the page.

Here you can see the page right after loading.

And here right after I used inspect element, which resizes the window.

Link to the page if you want to see it yourself.

Is there a way to display this as it should be with custom CSS or JS?

I understand its not a lot to work with, I'll be happy to provide more information if needed.

答:
I don't know much about wordpress and certainly i don't know anything about this gallery plugin that you are using, and this is not a solution, this is a workaround, so if anyone post an actual solution, you should try to fix this issue.

I've noticed that you, or some plugin has imported jQuery, so we will use it.

(function () {
  function triggerFakeResizeEvent () {
    window.dispatchEvent(new CustomEvent('resize'));
  }
  if (jQuery.isReady) {
    triggerFakeResizeEvent();
  } else {
    jQuery.ready(triggerFakeResizeEvent);
  }
})()
```

<p>If the page is already fully loaded it will trigger a fake resize event, otherwise it will wait until the page loads and then it will trigger such event.</p>

<p>Im not sure how much control you have over placing custom JavaScript in Wordpress, but it is important that this code will be executed after jQuery and your gallery plugin has been loaded.</p>

<p>If you can't do this, or the console says things like <code>jQuery is not defined</code>, try placing this instead</p>

<pre class="lang-js prettyprint-override"><code>  (function (){
    function triggerFakeResizeEvent () {
      window.dispatchEvent(new CustomEvent('resize'));
    }
    triggerFakeResizeEvent()
    document.addEventListener('DOMContentLoaded', triggerFakeResizeEvent);
  })()
</code>```

Title: Gallery grid not displaying properly

Body:
I don't know much about wordpress and certainly i don't know anything about this gallery plugin that you are using, and this is not a solution, this is a workaround, so if anyone post an actual solution, you should try to fix this issue.

I've noticed that you, or some plugin has imported jQuery, so we will use it.

(function () {
  function triggerFakeResizeEvent () {
    window.dispatchEvent(new CustomEvent('resize'));
  }
  if (jQuery.isReady) {
    triggerFakeResizeEvent();
  } else {
    jQuery.ready(triggerFakeResizeEvent);
  }
})()

If the page is already fully loaded it will trigger a fake resize event, otherwise it will wait until the page loads and then it will trigger such event.

Im not sure how much control you have over placing custom JavaScript in Wordpress, but it is important that this code will be executed after jQuery and your gallery plugin has been loaded.

If you can't do this, or the console says things like jQuery is not defined, try placing this instead

  (function (){
    function triggerFakeResizeEvent () {
      window.dispatchEvent(new CustomEvent('resize'));
    }
    triggerFakeResizeEvent()
    document.addEventListener('DOMContentLoaded', triggerFakeResizeEvent);
  })()


问:
waiting pg start for docker run
i have this error:

(node:51) UnhandledPromiseRejectionWarning: Error: getaddrinfo
  ENOTFOUND ${DB_HOST}

And then I found out that the problem was with my docker-compose
basically postgres is not initialized and so I'm having this error

I tried to use the following comand:

```<code>command: ['./wait-for-it/wait-for-it.sh', 'db:5432', '--', 'yarn', 'dev']
</code>```

but i got this error:

```<code>api    | internal/modules/cjs/loader.js:969
ci-api    |   throw err;
ci-api    |   ^
ci-api    |
ci-api    | Error: Cannot find module '/home/node/api/wait-for-it/wait-for-it.sh'
ci-api    |     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
ci-api    |     at Function.Module._load (internal/modules/cjs/loader.js:842:27)
ci-api    |     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
ci-api    |     at internal/main/run_main_module.js:17:47 {
ci-api    |   code: 'MODULE_NOT_FOUND',
ci-api    |   requireStack: []
ci-api    | }
</code>```

my docker file:

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

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD ["yarn", "dev"]
</code>```

my docker-compose:

```<code>version: '3.7'
services:
  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data

  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - db-pg
    command: ['./wait-for-it/wait-for-it.sh', 'db:5432', '--', 'yarn', 'dev']
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

volumes:
  ci-postgres-data:
</code>```

i would like to know how i could solve this

答: I never had this problem, but it seems to me that you have not your env variable ${DB_HOST} set correctly. In case you are using all internal with this docker-compose file, you should connect it to db-pg:5432 </p>

Title: waiting pg start for docker run

Body:
i have this error:

(node:51) UnhandledPromiseRejectionWarning: Error: getaddrinfo
  ENOTFOUND ${DB_HOST}

And then I found out that the problem was with my docker-compose
basically postgres is not initialized and so I'm having this error

I tried to use the following comand:

command: ['./wait-for-it/wait-for-it.sh', 'db:5432', '--', 'yarn', 'dev']

but i got this error:

api    | internal/modules/cjs/loader.js:969
ci-api    |   throw err;
ci-api    |   ^
ci-api    |
ci-api    | Error: Cannot find module '/home/node/api/wait-for-it/wait-for-it.sh'
ci-api    |     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
ci-api    |     at Function.Module._load (internal/modules/cjs/loader.js:842:27)
ci-api    |     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
ci-api    |     at internal/main/run_main_module.js:17:47 {
ci-api    |   code: 'MODULE_NOT_FOUND',
ci-api    |   requireStack: []
ci-api    | }

my docker file:

FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD ["yarn", "dev"]

my docker-compose:

version: '3.7'
services:
  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data

  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - db-pg
    command: ['./wait-for-it/wait-for-it.sh', 'db:5432', '--', 'yarn', 'dev']
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

volumes:
  ci-postgres-data:

i would like to know how i could solve this


问:
In Keras, why is the attribute decay in SGD considered to be left in only for backward compatibility?
Reading Keras-SGD I read the following.

..., decay is included for backward compatibility to allow time
inverse decay of learning rate. lr is included for backward
compatibility, recommended to use learning_rate instead.

Should decay no longer be used (doubtful) or is there another location to set it or is it replaced by another property? Why is Keras considering 'decay' only to be "included for backward compatibility."

答: It isn't marked for deprecation anywhere in docs or warnings, nor does it say "only", but it is suggestive of better available alternatives. One reason to avoid it is that a permanently decayed LR is seldom desirable (which is what it accomplishes), and it's hard to predict what a good value of decay should be ahead of time. From source code, it decays with 1 / (1 + iterations * decay). For alternatives and further details, refer to this answer.


问:
Angular 5: clicked button that triggers a dialog becomes highlighted after the dialog is closed
I noticed that button gets classes cdk-focused and cdk-program-focused added after the dialog it triggered is closed. If I click anywhere effect disappears.

app.component.html [fragment]

```<code><mat-cell *matCellDef="let element">
  <span matTooltip="Delete" matTooltipPosition="right">
    <button mat-icon-button color="warn" (click)="openDeleteAssociationDialog()">
      <mat-icon>delete</mat-icon>
    </button>
  </span>
</mat-cell>
</code>```

答:
This style fixed for me:</p>

```<code>.mat-button, .mat-flat-button, .mat-stroked-button
{
    &.cdk-program-focused .mat-button-focus-overlay
    {
        opacity: 0 !important;
    }
}
</code>```

Body:
I noticed that button gets classes cdk-focused and cdk-program-focused added after the dialog it triggered is closed. If I click anywhere effect disappears.

app.component.html [fragment]

<mat-cell *matCellDef="let element">

    <button mat-icon-button color="warn" (click)="openDeleteAssociationDialog()">
      <mat-icon>delete</mat-icon>
    </button>

</mat-cell>

Body:
This style fixed for me:

.mat-button, .mat-flat-button, .mat-stroked-button
{
    &.cdk-program-focused .mat-button-focus-overlay
    {
        opacity: 0 !important;
    }
}


问:
Stack Based Column Sum in a data frame using R
My existing data frame looks line given below

```<code>NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    3.581
2013-06-15  276.0  2013  Saturday  3.623   1000    3.623
2013-06-22  261.6  2013  Saturday  3.822   1000    3.822
2013-06-29  273.3  2013  Saturday  3.659   1000    3.659
</code>```

I want my new data frame to have Balance_Units column have entries like given below using R Language
i.e Balance unit column should be the sum of previous value and present value
This is need to be done on the list of dataframe

```<code>NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    7.121
2013-06-15  276.0  2013  Saturday  3.623   1000    10.744
2013-06-22  261.6  2013  Saturday  3.822   1000    14.566
2013-06-29  273.3  2013  Saturday  3.659   1000    18.225
</code>```

I tried this but , this is not working

```<code> for( i in 1:length(W)) {
  W[[i]]$Units  = 1000/W[[i]]$NAV
  W[[i]]$Amount = 1000
  W[[i]]$Balance_Units = 0
  W[[i]]$Balance_Units = W[[i]]$Units + W[[i]]$Balance_Units
   }
</code>```

答:
This can be done with a convenient function cumsum in base R

```<code>df1$Balance_Units <- cumsum(df1$Balance_Units)
</code>```

With dplyr, it can be created within mutate

```<code>library(dplyr)
df1 %>%
    mutate(Balance_Units = cumsum(Balance_Units))
</code>```

If 'W' is a list of data.frames, we can use lapply

```<code>W <- lapply(W, transform, Balance_Units = cumsum(Balance_Units))
</code>```

data

```<code>df1 <- structure(list(NAV_Date = c("2013-06-01", "2013-06-08", "2013-06-15",
"2013-06-22", "2013-06-29"), NAV = c(282.5, 279.3, 276, 261.6,
273.3), Year = c(2013L, 2013L, 2013L, 2013L, 2013L), Day = c("Saturday",
"Saturday", "Saturday", "Saturday", "Saturday"), Units = c(3.54,
3.581, 3.623, 3.822, 3.659), Amount = c(1000L, 1000L, 1000L,
1000L, 1000L), Balance_Units = c(3.54, 3.581, 3.623, 3.822, 3.659
)), class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
My existing data frame looks line given below

NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    3.581
2013-06-15  276.0  2013  Saturday  3.623   1000    3.623
2013-06-22  261.6  2013  Saturday  3.822   1000    3.822
2013-06-29  273.3  2013  Saturday  3.659   1000    3.659

I want my new data frame to have Balance_Units column have entries like given below using R Language
i.e Balance unit column should be the sum of previous value and present value
This is need to be done on the list of dataframe

NAV_Date    NAV    Year  Day       Units   Amount  Balance_Units
2013-06-01  282.5  2013  Saturday  3.540   1000    3.540
2013-06-08  279.3  2013  Saturday  3.581   1000    7.121
2013-06-15  276.0  2013  Saturday  3.623   1000    10.744
2013-06-22  261.6  2013  Saturday  3.822   1000    14.566
2013-06-29  273.3  2013  Saturday  3.659   1000    18.225

I tried this but , this is not working

 for( i in 1:length(W)) {
  W[[i]]$Units  = 1000/W[[i]]$NAV
  W[[i]]$Amount = 1000
  W[[i]]$Balance_Units = 0
  W[[i]]$Balance_Units = W[[i]]$Units + W[[i]]$Balance_Units
   }

Body:
This can be done with a convenient function cumsum in base R

df1$Balance_Units <- cumsum(df1$Balance_Units)

With dplyr, it can be created within mutate

library(dplyr)
df1 %>%
    mutate(Balance_Units = cumsum(Balance_Units))

If 'W' is a list of data.frames, we can use lapply

W <- lapply(W, transform, Balance_Units = cumsum(Balance_Units))

data

df1 <- structure(list(NAV_Date = c("2013-06-01", "2013-06-08", "2013-06-15",
"2013-06-22", "2013-06-29"), NAV = c(282.5, 279.3, 276, 261.6,
273.3), Year = c(2013L, 2013L, 2013L, 2013L, 2013L), Day = c("Saturday",
"Saturday", "Saturday", "Saturday", "Saturday"), Units = c(3.54,
3.581, 3.623, 3.822, 3.659), Amount = c(1000L, 1000L, 1000L,
1000L, 1000L), Balance_Units = c(3.54, 3.581, 3.623, 3.822, 3.659
)), class = "data.frame", row.names = c(NA, -5L))


问:
Android emulator errors (socketTcpLoopbackClientFor and AdbHostServer.cpp)
I just installed Android Studio (Windows) and I created a google pixel 3 XL, API 29, no play store installed.
When I launch an hello word application, I get these 2 errors:

```<code>Emulator: socketTcpLoopbackClientFor: error: fd 52252 above FD_SETSIZE (32768)
Emulator: emulator: ERROR: AdbHostServer.cpp:102: Unable to connect to adb daemon on port: 5037
</code>```

For what concerning the first error, I tried this Problem with the emulator since the update but it didn't work.

答:
I am not sure if it is helpfull but I will share my experience as a possible answer. I struggled for three days trying to face a very similar issue as yours. And in my case it was working properlly until that. I created a question here but I din't get answer yet. Well, I tried all I found around. Then I read somewhere someone facing issues with emulator and just downground it and it fixed it. I just tried downgraded from Android 10+ to Android 10 and to API #29 and I got a complete diferent issue. Than I tried again to Android 9 and API #28 and it fixed my issue.

One more thing it can be usefull. I noted that before I downgraded Android/API I had many more for this list

```<code>C:\Users>netstat -ano | findstr "5037"
  TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       7892
  TCP    127.0.0.1:5037         127.0.0.1:49735        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51843        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51855        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51859        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51867        ESTABLISHED     7892
  TCP    127.0.0.1:49735        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51843        127.0.0.1:5037         ESTABLISHED     13184
  TCP    127.0.0.1:51855        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51859        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51867        127.0.0.1:5037         ESTABLISHED     9604
</code>```

And maybe checking you SDk Tools installed can help also

Body:
I just installed Android Studio (Windows) and I created a google pixel 3 XL, API 29, no play store installed.
When I launch an hello word application, I get these 2 errors:

Emulator: socketTcpLoopbackClientFor: error: fd 52252 above FD_SETSIZE (32768)
Emulator: emulator: ERROR: AdbHostServer.cpp:102: Unable to connect to adb daemon on port: 5037

For what concerning the first error, I tried this Problem with the emulator since the update but it didn't work.

Body:
I am not sure if it is helpfull but I will share my experience as a possible answer. I struggled for three days trying to face a very similar issue as yours. And in my case it was working properlly until that. I created a question here but I din't get answer yet. Well, I tried all I found around. Then I read somewhere someone facing issues with emulator and just downground it and it fixed it. I just tried downgraded from Android 10+ to Android 10 and to API #29 and I got a complete diferent issue. Than I tried again to Android 9 and API #28 and it fixed my issue.

One more thing it can be usefull. I noted that before I downgraded Android/API I had many more for this list

C:\Users>netstat -ano | findstr "5037"
  TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       7892
  TCP    127.0.0.1:5037         127.0.0.1:49735        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51843        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51855        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51859        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51867        ESTABLISHED     7892
  TCP    127.0.0.1:49735        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51843        127.0.0.1:5037         ESTABLISHED     13184
  TCP    127.0.0.1:51855        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51859        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51867        127.0.0.1:5037         ESTABLISHED     9604

And maybe checking you SDk Tools installed can help also


问:
How to Add a "Go Back" Toggle
I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading.

I know I just write Previous but I don't know the javascript to go back.

$(function() {

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next```

答:
You could add an index using data attribute and then check its value to set show hide using a next/previous method in jquery...

I set a variable for data and tehn incremented it with next() or prev() depending on where the next or previous button was clicked. Hide the previous button if the info = 1 and show next button, hide next if data = length of elements and show previous...

$(function() {
  let data;
  let len = $('.msg').length;
  $('.js-button').click(function() {

    if ($(this).hasClass('next')) {
      data = $('div.active').next().data('info');
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }
    } else if ($(this).hasClass('previous')) {
      data = $('div.active').prev().data('info');
      if ($('div.active').prev().hasClass('hidemsg')) {
        $('div.active').prev('div').addClass('active').end().removeClass('active');
      }
    }

    if (data === 1) {
      $('.previous').hide();
      $('.next').show();
    }
    if (data > 1) {
      $('.previous').show();
    }
    if (data > 4) {
      $('.next').hide();
    }

    console.log(len, data)

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidemsg {
  display: none;
}

.hidemsg.active {
  display: block;
}

.previous {
  display: none;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

    1) Info here

    2) Info Here

    3) Info Here

    4) Info Here

    5) Info Here

Next
Previous```

Title: How to Add a "Go Back" Toggle

Body:
I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading.

I know I just write Previous but I don't know the javascript to go back.

$(function() {

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });
});

.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next

Body:
You could add an index using data attribute and then check its value to set show hide using a next/previous method in jquery...

I set a variable for data and tehn incremented it with next() or prev() depending on where the next or previous button was clicked. Hide the previous button if the info = 1 and show next button, hide next if data = length of elements and show previous...

$(function() {
  let data;
  let len = $('.msg').length;
  $('.js-button').click(function() {

    if ($(this).hasClass('next')) {
      data = $('div.active').next().data('info');
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }
    } else if ($(this).hasClass('previous')) {
      data = $('div.active').prev().data('info');
      if ($('div.active').prev().hasClass('hidemsg')) {
        $('div.active').prev('div').addClass('active').end().removeClass('active');
      }
    }

    if (data === 1) {
      $('.previous').hide();
      $('.next').show();
    }
    if (data > 1) {
      $('.previous').show();
    }
    if (data > 4) {
      $('.next').hide();
    }

    console.log(len, data)

  });
});

.hidemsg {
  display: none;
}

.hidemsg.active {
  display: block;
}

.previous {
  display: none;
}

<!DOCTYPE html>
<html lang="en" class="no-js.june">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<div data-info="1" id="msg1" class="msg hidemsg active first">
  <p class="content__item-copy-text">
    1) Info here
  </p>
</div>

<div data-info="2" id="msg2" class="msg hidemsg">
  <p class="content__item-copy-text">
    2) Info Here </p>
</div>

<div data-info="3" id="msg3" class="msg hidemsg">
  <p class="content__item-copy-text">
    3) Info Here </p>
</div>

<div data-info="4" id="msg4" class="msg hidemsg">
  <p class="content__item-copy-text">
    4) Info Here </p>
</div>

<div data-info="5" id="msg5" class="msg hidemsg last">
  <p class="content__item-copy-text">
    5) Info Here </p>
</div>
<a href="#" type="button" class="btn btn-default js-button next">Next</a>
<a href="#" type="button" class="btn btn-default js-button previous">Previous</a>


问:
can't populate table because of vague syntax error
I'm trying to populate one table from my database on phpmyadmin, so I have this script:

```<code>USE avi; //database

SET @listOfStates = 'AK, AL, AR, AS, AZ, CA, CO, CT, DC, DE, FL, GA, GU, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MN, MO, MP, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, PR, RI, SC, SD, TN, TX, UM, UT, VA, VI, VT, WA, WI, WV, WY';

SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
SET @itemValue = 0;

CREATE PROCEDURE populate()
BEGIN
SET @strLen = LENGTH(@listOfStates);

label1: LOOP

    SET @strLen = LENGTH(@listOfStates);
    SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
    SELECT COUNT(*) INTO @itemValue FROM us_accidents u WHERE u.state LIKE item;

    INSERT INTO state_cases (name, cases) VALUES (@item, @itemValue);

    SET @SubStrLen = LENGHT(SUBSTRING_INDEX(listOfStates, ',', 1));
    SET @listOfStates =  MID(listOfStates, SubStrLen, strLen);

    IF listOfStates = NULL
        LEAVE label1;
    ITERATE label1;

    END LOOP label1;

END;

</code>```

when I'm trying to import I get this

Am I using SET @ wrong? or is something wrong with my procedures or even the varchar?

I mention that the table is already created.

答:
Your primary problem is that you are missing the DELIMITER command before the start of the stored procedure.

Also, the IF statement at the end of the procedure is malformed: the syntax is IF ... THEN ... END IF;. And, finally, to check for nullness you need IS NULL rather than = NULL.

This compiles successfully:

```<code>SET @listOfStates = 'AK, AL, AR, AS, AZ, CA, CO, CT, DC, DE, FL, GA, GU, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MN, MO, MP, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, PR, RI, SC, SD, TN, TX, UM, UT, VA, VI, VT, WA, WI, WV, WY';

SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
SET @itemValue = 0;

DELIMITER //

CREATE PROCEDURE populate()
BEGIN
    SET @strLen = LENGTH(@listOfStates);

    label1: LOOP

        SET @strLen = LENGTH(@listOfStates);
        SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
        SELECT COUNT(*) INTO @itemValue FROM us_accidents u WHERE u.state LIKE item;

        INSERT INTO state_cases (name, cases) VALUES (@item, @itemValue);

        SET @SubStrLen = LENGHT(SUBSTRING_INDEX(listOfStates, ',', 1));
        SET @listOfStates =  MID(listOfStates, SubStrLen, strLen);

        IF listOfStates IS NULL THEN
            LEAVE label1;
        END IF;

        ITERATE label1;

    END LOOP label1;

END;
//

DELIMITER ;
</code>```

Body:
I'm trying to populate one table from my database on phpmyadmin, so I have this script:

USE avi; //database

SET @listOfStates = 'AK, AL, AR, AS, AZ, CA, CO, CT, DC, DE, FL, GA, GU, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MN, MO, MP, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, PR, RI, SC, SD, TN, TX, UM, UT, VA, VI, VT, WA, WI, WV, WY';

SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
SET @itemValue = 0;

CREATE PROCEDURE populate()
BEGIN
SET @strLen = LENGTH(@listOfStates);

label1: LOOP

    SET @strLen = LENGTH(@listOfStates);
    SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
    SELECT COUNT(*) INTO @itemValue FROM us_accidents u WHERE u.state LIKE item;

    INSERT INTO state_cases (name, cases) VALUES (@item, @itemValue);

    SET @SubStrLen = LENGHT(SUBSTRING_INDEX(listOfStates, ',', 1));
    SET @listOfStates =  MID(listOfStates, SubStrLen, strLen);

    IF listOfStates = NULL
        LEAVE label1;
    ITERATE label1;

    END LOOP label1;

END;

when I'm trying to import I get this

Am I using SET @ wrong? or is something wrong with my procedures or even the varchar?

I mention that the table is already created.

Body:
Your primary problem is that you are missing the DELIMITER command before the start of the stored procedure.

Also, the IF statement at the end of the procedure is malformed: the syntax is IF ... THEN ... END IF;. And, finally, to check for nullness you need IS NULL rather than = NULL.

This compiles successfully:

SET @listOfStates = 'AK, AL, AR, AS, AZ, CA, CO, CT, DC, DE, FL, GA, GU, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MN, MO, MP, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, PR, RI, SC, SD, TN, TX, UM, UT, VA, VI, VT, WA, WI, WV, WY';

SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
SET @itemValue = 0;

DELIMITER //

CREATE PROCEDURE populate()
BEGIN
    SET @strLen = LENGTH(@listOfStates);

    label1: LOOP

        SET @strLen = LENGTH(@listOfStates);
        SET @item = SUBSTRING_INDEX(@listOfStates, ',', 1);
        SELECT COUNT(*) INTO @itemValue FROM us_accidents u WHERE u.state LIKE item;

        INSERT INTO state_cases (name, cases) VALUES (@item, @itemValue);

        SET @SubStrLen = LENGHT(SUBSTRING_INDEX(listOfStates, ',', 1));
        SET @listOfStates =  MID(listOfStates, SubStrLen, strLen);

        IF listOfStates IS NULL THEN
            LEAVE label1;
        END IF;

        ITERATE label1;

    END LOOP label1;

END;
//

DELIMITER ;


问:
String manipulation, removing a single comma
UPDATE 1:

This is how I am attempting to build the string:

```<code>header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}
</code>```

ORIGINAL QUESTION:

I have a string similar to this:

```<code>$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";
</code>```

How do I remove the last comma?

答:
get the position of the reverse of the string first

stripos(',', strrev($myString))

then you can do whatever you want, replace it, delete it, up to you.

Body:
UPDATE 1:

This is how I am attempting to build the string:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}

ORIGINAL QUESTION:

I have a string similar to this:

$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";

How do I remove the last comma?


问:
Customize creating account
I have a small question, I'm using wordpress, when I'm creating an user account is it possible to add a birth date parameter ? I don't know how to use php, does a plugin exist to customize it ?
I have search but couldn't find anything TT

Thank you for you response and sorry for my English ^^'

答:
This is the plugin you're want to try.  I wouldn't do this with a plugin but if you don't know PHP or other coding methods then this is probably your best option.

https://wordpress.org/plugins/user-meta/

Title: Customize creating account


问:
How to get the member count in discord.py rewrite?
I wanted to make an command to show the membercount but it doesn't work.

This is what I have:

```<code>@bot.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))
</code>```

and this is the error i get:
Module 'discord.guild' has no 'member_count' member

I tried searching on the internet but didn't find a working option.

答:
Enable Developer mode in Discord (User Settings -> Accessibility) then right click the server icon and click Copy ID, then type this line of code after async def:
guild = client.get_guild(paste the copied ID here)
Also you don't need len(guild.member_count) it will return number of digits of member count. Use guild.member_count only.

Hope this helped

Body:
I wanted to make an command to show the membercount but it doesn't work.

This is what I have:

@bot.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))

and this is the error i get:
Module 'discord.guild' has no 'member_count' member

I tried searching on the internet but didn't find a working option.


问:
Filter divs by class
I am trying to create a function that returns an additional display of none when you click on a button. It basically filters divs with class names when you click a button. I used a while/do loop to go through all the elements by class name.
In the browser console log it is telling me

"Cannot read property 'style' of undefined".

Does anybody knows what might be the problem?

```<code>    <div class="container">
      <h1 id="title">World's Top suppply chains</h1>
        <div class="options">
          <button id="allbtn">All</button>
          <button>Drinks</button>
          <button>Clothing</button>
          <button>Cars</button>
          <button id="fast-food-btn">Fast Food</button>
    </div>

    <div class="stores">
        <div class="store">
            <img src="images/adidas.png">
            <h3>Adidas</h3>
            <p class="industry">Clothing</p>
        </div>

        <div class="store">
            <img src="images/corona.png">
            <h3>Corona</h3>
            <p class="industry">Drinks</p>
        </div>

        <div class="store">
            <img src="images/nike.jpg">
            <h3>Nike</h3>
            <p class="industry">Clothing</p>
        </div>

        <div class="store">
            <img src="images/lambo.png">
            <h3>Lamborghini</h3>
            <p class="industry">Cars</p>
        </div>

        <div class="store">
            <img src="images/smirnoff.png">
            <h3>Smirnoff</h3>
            <p class="industry">Drinks</p>
        </div>

        <div class="store">
            <img src="images/pepsi.jpg">
            <h3>Pepsi</h3>
            <p class="industry">Drinks</p>
        </div>

        <div class="store">
            <img src="images/gucci.png">
            <h3>Gucci</h3>
            <p class="industry">Clothing</p>
        </div>

          <div class="store">
            <img src="images/heineken.jpg">
            <h3>Heineken</h3>
            <p class="industry">Drinks</p>
        </div>

        <div class="store">
            <img src="images/lacoste.png">
            <h3>Lacoste</h3>
            <p class="industry">Clothing</p>
        </div>

        <div class="store">
            <img src="images/ferrari.png">
            <h3>Ferrari</h3>
            <p class="industry">Cars</p>
        </div>

      <div class="store">
            <img src="images/pizzahut.png">
            <h3>Pizza Hut</h3>
            <p class="industry">Fast Food</p>
        </div>

      <div class="store">
            <img src="images/cocacola.png">
            <h3>Coca Cola</h3>
            <p class="industry">Drinks</p>
        </div>

        <div class="store">
            <img src="images/mc.png">
            <h3>Mc Donalds</h3>
            <p class="industry">Fast Food</p>
        </div>
    </div>
</div>

<script>
    const industry = document.getElementsByClassName(".industry");
    const fastFood = document.getElementById("fast-food-btn");

    allbtn.addEventListener("click", filter);

    function filter(){

        const card = industry.parentElement;

    do{
         card.style.display = "none";
    }
        while(industry.innerHTML === "Fast Food");
    }

</script>
</code>```

答:
First issue is that you don't need the dot in front of the class when using getElementsByClassName.
Secondly getElementsByClassName returns a HTMLCollection which does not have a property called parent.

Which results in something like this:

```<code>function filter() {
    const industries = document.getElementsByClassName("industry");
    for (let industry of industries) {
        industry.style.display = "none";
    }
}

</code>```

Furthermore, it looks like the variable fastFood is not used and the variable allbtn is undefined. I assume it shoul be something like this:

```<code>const allbtn = document.getElementById("allbtn");
</code>```

Putting it together, this should solve your problem:

```<code><script>
    function filter() {
        const industries = document.getElementsByClassName("industry");
        for (let industry of industries) {
            industry.style.display = "none";
        }
    }
    const allbtn = document.getElementById("allbtn");
    allbtn.addEventListener("click", filter);
</script>
</code>```

Title: Filter divs by class

Body:
I am trying to create a function that returns an additional display of none when you click on a button. It basically filters divs with class names when you click a button. I used a while/do loop to go through all the elements by class name.
In the browser console log it is telling me

"Cannot read property 'style' of undefined".

Does anybody knows what might be the problem?

World's Top suppply chains

          <button id="allbtn">All</button>
          <button>Drinks</button>
          <button>Clothing</button>
          <button>Cars</button>
          <button id="fast-food-btn">Fast Food</button>

Adidas

Clothing

Corona

Drinks

Nike

Clothing

Lamborghini

Cars

Smirnoff

Drinks

Pepsi

Drinks

Gucci

Clothing

Heineken

Drinks

Lacoste

Clothing

Ferrari

Cars

Pizza Hut

Fast Food

Coca Cola

Drinks

Mc Donalds

Fast Food

Body:
First issue is that you don't need the dot in front of the class when using getElementsByClassName.
Secondly getElementsByClassName returns a HTMLCollection which does not have a property called parent.

Which results in something like this:

function filter() {
    const industries = document.getElementsByClassName("industry");
    for (let industry of industries) {
        industry.style.display = "none";
    }
}

Furthermore, it looks like the variable fastFood is not used and the variable allbtn is undefined. I assume it shoul be something like this:

const allbtn = document.getElementById("allbtn");

Putting it together, this should solve your problem:

<script>
    function filter() {
        const industries = document.getElementsByClassName("industry");
        for (let industry of industries) {
            industry.style.display = "none";
        }
    }
    const allbtn = document.getElementById("allbtn");
    allbtn.addEventListener("click", filter);
</script>