问:
Modal only showing last in Database
I am new to databases and PHP, so my knowledge of their integration is extremely limited. I have a list showing on my site and each item has a button that links to a modal. I am trying to have each modal open up correspond with the id of the item listed. Instead, it is only showing the last item in the database list.

I have tried adding code that I have seen from online searches, but nothing seems to work. I want to avoid AJAX, JS, and JQuery. I don't really think that it needs that. It seems to just be a syntax error.

```<code>    <div class="recentUploads col-md-8">

        <!-- Magic Key --- CONNECTS or PLUGS-IN to the DATABSE -->
        <?php include("_inc/database_key.php"); ?>

        <!-- REQUEST specific information -->
        <?
            $sql = "SELECT * FROM `comic book collection` ORDER BY id";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
        ?>

        <!-- DISPLAY that specific information -->
        <?php
            echo '<div class="comic_book_card row">';

                $id=$row["id"];

                echo '<div class="cover col-3"><img style="width: 100%;" src="'.$row["picture"].'"></div>';

                echo '<div class="comic-info col-8">';
                    echo '<h2>#'.$row["issue"].' '.$row["title"].'</h2>';
                    echo '<h6>'.$row["publisher"].' | '.$row["event"].'</h6>';
                    echo '<h6>'.$row["month"].' '.$row["day"].', '.$row["year"].'</h6>';

                    echo '<button id="modal-btn" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#details" >More Info</button>';
                    echo '<form><input type="hidden" id="id" name="id" value="'.$row["id"].'"</form>';
                echo '</div>';

            echo '</div>';

        ?>

        <!-- IM DONE - CLOSE the connection -->
        <?php
            }
            } else {
            echo "0 results";
            }
            $conn->close();
        ?>

    </div>
</code>```

        Details
        ×

          " allowfullscreen>

        Close

答:
Try This Code :-

```<code> <div class="recentUploads col-md-8">
        <?php include("_inc/database_key.php"); ?>
        <?
            $sql = "SELECT * FROM `comic book collection` ORDER BY id";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
           $output="";
           while($row = $result->fetch_assoc()) {
                    $id=$row["id"];

        $output.='<div class="comic_book_card row">
        <div class="cover col-3"><img style="width: 100%;" src="'.$row["picture"].'"></div>
        <div class="comic-info col-8">
        <h2>#'.$row["issue"].' '.$row["title"].'</h2>
        <h6>'.$row["publisher"].' | '.$row["event"].'</h6>
        <h6>'.$row["month"].' '.$row["day"].', '.$row["year"].'</h6>
        <button id="modal-btn" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#details" >More Info</button>
        <form><input type="hidden" id="id" name="id" value="'.$row["id"].'"/></form>
        </div></div>';

        ?>

         }
    </div>

    <?php echo $output; ?>
</code>```

Title: Modal only showing last in Database

Body:
I am new to databases and PHP, so my knowledge of their integration is extremely limited. I have a list showing on my site and each item has a button that links to a modal. I am trying to have each modal open up correspond with the id of the item listed. Instead, it is only showing the last item in the database list.

I have tried adding code that I have seen from online searches, but nothing seems to work. I want to avoid AJAX, JS, and JQuery. I don't really think that it needs that. It seems to just be a syntax error.

        <?php include("_inc/database_key.php"); ?>

        <?
            $sql = "SELECT * FROM `comic book collection` ORDER BY id";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
        ?>

        <?php
            echo '
';

                $id=$row["id"];

                echo '

';

                echo '
';
                    echo '
#'.$row["issue"].' '.$row["title"].'
';
                    echo '
'.$row["publisher"].' | '.$row["event"].'
';
                    echo '
'.$row["month"].' '.$row["day"].', '.$row["year"].'
';

                    echo '<button id="modal-btn" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#details" >More Info</button>';
                    echo '<form><input type="hidden" id="id" name="id" value="'.$row["id"].'"</form>';
                echo '
';

            echo '
';

        ?>

        <?php
            }
            } else {
            echo "0 results";
            }
            $conn->close();
        ?>

        Details
        ×

          " allowfullscreen>

        Close

Body:
Try This Code :-

 <div class="recentUploads col-md-8">
        <?php include("_inc/database_key.php"); ?>
        <?
            $sql = "SELECT * FROM `comic book collection` ORDER BY id";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
           $output="";
           while($row = $result->fetch_assoc()) {
                    $id=$row["id"];

        $output.='<div class="comic_book_card row">
        <div class="cover col-3"><img style="width: 100%;" src="'.$row["picture"].'"></div>
        <div class="comic-info col-8">
        <h2>#'.$row["issue"].' '.$row["title"].'</h2>
        <h6>'.$row["publisher"].' | '.$row["event"].'</h6>
        <h6>'.$row["month"].' '.$row["day"].', '.$row["year"].'</h6>
        <button id="modal-btn" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#details" >More Info</button>
        <form><input type="hidden" id="id" name="id" value="'.$row["id"].'"/></form>
        </div></div>';

        ?>

         }
    </div>

    <?php echo $output; ?>


来源: stackexchange

问:
htaccess redirect add querystring

I'm triying to redirect www.myweb.com to www.myweb.com/?lang=en

Any try i made redirect all the traffic in the website or creates a loop.

Any help?

答:
If you need to do it via a rewrite rule for whatever reason, this worked for the simple example I tried:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ $1?lang=en [QSA]
</code>```

Though there are similar questions on stack overflow you should check out: ModRewite and general searching ;)

ContentLicense: CC BY-SA 3.0

Title: htaccess redirect add querystring

Body:
If you need to do it via a rewrite rule for whatever reason, this worked for the simple example I tried:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ $1?lang=en [QSA]

Though there are similar questions on stack overflow you should check out: ModRewite and general searching ;)


问:
Generate Bitmap from httpRequest body
I'm sending an image via Postman

I want to use the image as an Bitmap in my function.

I am trying

```<code>  public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("IsFundusCalled");

            string name = req.Query["image"];
            var imageData = ReadFully(req.Body);
            Bitmap image;
            using (var ms = new MemoryStream(imageData))
            {
                image = new Bitmap(ms);
            }
            MemoryStream memoryStream = new MemoryStream();
            image.Save(memoryStream, ImageFormat.Jpeg);

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
            httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            httpResponseMessage.StatusCode = HttpStatusCode.OK;

            return httpResponseMessage;
        }

        //from https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
</code>```

but i am getting the error:
"System.Private.CoreLib: Exception while executing function: IsFundus. ZKWeb.System.Drawing: A null reference or invalid value was found [GDI+ status: InvalidParameter]."
from : image.Save(memoryStream, ImageFormat.Jpeg);

答: Instead of uploading your image as Form-data, upload it as binary in postman and it should work just fine. Your Function code looks ok so far. (I would remove the "get" though, in the Function header, as only POST really makes sense for your case)</p>

ContentLicense: CC BY-SA 4.0

Title: Generate Bitmap from httpRequest body

Body:
I'm sending an image via Postman

I want to use the image as an Bitmap in my function.

I am trying

  public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("IsFundusCalled");

            string name = req.Query["image"];
            var imageData = ReadFully(req.Body);
            Bitmap image;
            using (var ms = new MemoryStream(imageData))
            {
                image = new Bitmap(ms);
            }
            MemoryStream memoryStream = new MemoryStream();
            image.Save(memoryStream, ImageFormat.Jpeg);

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
            httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            httpResponseMessage.StatusCode = HttpStatusCode.OK;

            return httpResponseMessage;
        }

        //from https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream
        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

but i am getting the error:
"System.Private.CoreLib: Exception while executing function: IsFundus. ZKWeb.System.Drawing: A null reference or invalid value was found [GDI+ status: InvalidParameter]."
from : image.Save(memoryStream, ImageFormat.Jpeg);


问:
Build failed after update coroutines to 1.2.0: META-INF/atomicfu.kotlin_module
After update to org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.0 android build failed with issue:
More than one file was found with OS independent path 'META-INF/atomicfu.kotlin_module'

Are there any workaround to make it work?

答:
Adding -dontwarn kotlinx.atomicfu.** to my proguard rules file was enough to get my build working with version 1.2.1 of the kotlinx-coroutines-android library.

Adding the packagingOptions { pickFirst('META-INF/atomicfu.kotlin_module') } or packagingOptions { exclude('META-INF/atomicfu.kotlin_module') } block in my build.gradle file didn't work.


问:
Configure Git in Powerbuilder 12.5
I would like to integrate my powerbuilder application with GIT Source version control.I would like to know a step by step process to configure git in my powerbuilder. My powerbuilder version is 12.5.

Thanks

答:
Not with 12.5.  There was a MSSCCI to Git bridge product from PB Software that worked with older versions of Git, but they don't seem to be around anymore:

http://www.pbsoftware.com/index.php/products/powerbuilder-git-msscci-provider/

Native support for Git (and SVN) was added to the 2017 R2 version of the product by Appeon.  I would suggest upgrading to the most recent version of the product (2019 comes out later this month) if you need to support Git:

https://community.appeon.com/index.php/articles/tutorials-articles/2-powerbuilder/183-powerbuilder-2017-r2-new-feature-git-source-control-support

Title: Configure Git in Powerbuilder 12.5


问:
How to write plain BigInteger in Spring controller
I need to return BigInteger from Spring controller in numeric format (such as 354736184430273859332531) instead of for example 2.2311485309166910602366e+23 which is default behavior.

I have tried including both: spring.jackson.serialization.write-bigdecimal-as-plain=true and
spring.jackson.generator.write-bigdecimal-as-plain=true in application.properties

My object which I'm returning looks like this:

```<code>data class ProductOutputDTO(
    val token: BigInteger,
    val product: BigInteger
)
</code>```

And controller code:

```<code>@RestController
class Product {

    @PostMapping("/product")
    fun product(@RequestBody input: ProductInputDTO): ProductOutputDTO
            = ProductOutputDTO(input.token, input.a * input.b)

}
</code>```

答:
Change your ProductOutputDTO to be something like the following example:

```<code>data class ProductOutputDTO(
    val token: String,
    val product: String
)
</code>```

Then change your code that creates the ProductOutputDTO to convert the BigIntegers to Strings.

The problem you are running into is that the JSON Number precision is not as precise as the BigInteger.

Body:
I need to return BigInteger from Spring controller in numeric format (such as 354736184430273859332531) instead of for example 2.2311485309166910602366e+23 which is default behavior.

I have tried including both: spring.jackson.serialization.write-bigdecimal-as-plain=true and
spring.jackson.generator.write-bigdecimal-as-plain=true in application.properties

My object which I'm returning looks like this:

data class ProductOutputDTO(
    val token: BigInteger,
    val product: BigInteger
)

And controller code:

@RestController
class Product {

    @PostMapping("/product")
    fun product(@RequestBody input: ProductInputDTO): ProductOutputDTO
            = ProductOutputDTO(input.token, input.a * input.b)

}

Body:
Change your ProductOutputDTO to be something like the following example:

data class ProductOutputDTO(
    val token: String,
    val product: String
)

Then change your code that creates the ProductOutputDTO to convert the BigIntegers to Strings.

The problem you are running into is that the JSON Number precision is not as precise as the BigInteger.


问:
Visual Studio Code - Python - List Index Limit Max 300 - Debugger
I have a list contains several hundred entries. I think the total size of the list is 3.5 MB.

When debugging an issue I can't seem to view any entry passed 300 and I see this message 'Too large to show contents. Max items to show: 300'

Any ideas?

答: I would advise using the debug console to manually poke and prod your data versus trying to look at all of it at once if it's that large and requires editing internal code to the debugger. The limit is there for a reason and so going past it could leave to issues.</p>


问:
RegEx for capturing a word in between = and ;
I want to select word2 from the following :

```<code>word2;word3
</code>```

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line
like word2 from

```<code>word1=word2;word3
</code>```

I have tried using this regex

```<code>(?<=\=|^).*?(?=;)
</code>```

which select the word2 from

```<code>word2;word3
</code>```

but also the whole word1=word2 from

```<code>word1=word2;word3
</code>```

答:
There should be so many options, maybe regular expressions among the last ones.

But, if we wish to use an expression for this problem, let's start with a simple one and explore other options, maybe something similar to:

```<code>(.+=)?(.+?);
</code>```

or

```<code>(.+=)?(.+?)(?:;.+)
</code>```

where the second capturing group has our desired word2.

Demo 1

Demo 2

Example 1

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.+=)?(.+?);";
        string input = @"word1=word2;word3
word2;word3";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

Example 2

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.+=)?(.+?)(?:;.+)";
        string substitution = @"$2";
        string input = @"word1=word2;word3
word2;word3";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}
</code>```

Body:
I want to select word2 from the following :

word2;word3

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line
like word2 from

word1=word2;word3

I have tried using this regex

(?<=\=|^).*?(?=;)

which select the word2 from

word2;word3

but also the whole word1=word2 from

word1=word2;word3

Body:
There should be so many options, maybe regular expressions among the last ones.

But, if we wish to use an expression for this problem, let's start with a simple one and explore other options, maybe something similar to:

(.+=)?(.+?);

or

(.+=)?(.+?)(?:;.+)

where the second capturing group has our desired word2.

Demo 1

Demo 2

Example 1

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.+=)?(.+?);";
        string input = @"word1=word2;word3
word2;word3";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

Example 2

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.+=)?(.+?)(?:;.+)";
        string substitution = @"$2";
        string input = @"word1=word2;word3
word2;word3";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}


问:
Regex exclude white space from selection
I was trying to search text contents inside a few html files using regex.

I have created a regex ((?<=>)[^<>]+?(?=([\s\r]*<))) that is working fine but search result also includes white spaces only values and leading white spaces.

test

                Type

```

The search result will have test,
               Type, and a few other results with white spaces only.
How can we remove white space only values and leading white spaces from search result?

答:
Try with this:

```<code>(?<=>)\s*+([^<>]+?(?=(?:[\s\r]*<)))
</code>```

You have a demo here.

The results will be at the first capturing group

This is what I changed from your original regex.

```<code> (?<=>)\s*+([^<>]+?(?=(?:[\s\r]*<)))
^      ^   ^          ^
|      |   |           \__ Used a non-caturing group (just recommended)
|      |   |
|      |   \___ This is now the begin of the capturing group
|      |
|      \___ Added whitespaces with possesive quantifier (cannot backtrack)
|
\__ Removed beginning of first capturing group
</code>```

Finally, if you wanted not using capturing group, and use just matches instead, you may use this regex:

```<code>(?<=>)\s*+\K[^<>]+?(?=(?:[\s\r]*<))
</code>```

It is similar to the previous one. The difference is that is uses \K to forget the current matching string.

You have a new demo here.

Body:
I was trying to search text contents inside a few html files using regex.

I have created a regex ((?<=>)[^<>]+?(?=([\s\r]*<))) that is working fine but search result also includes white spaces only values and leading white spaces.

test

                Type

The search result will have test,
               Type, and a few other results with white spaces only.
How can we remove white space only values and leading white spaces from search result?

Body:
Try with this:

(?<=>)\s*+([^<>]+?(?=(?:[\s\r]*<)))

You have a demo here.

The results will be at the first capturing group

This is what I changed from your original regex.

 (?<=>)\s*+([^<>]+?(?=(?:[\s\r]*<)))
^      ^   ^          ^
|      |   |           \__ Used a non-caturing group (just recommended)
|      |   |
|      |   \___ This is now the begin of the capturing group
|      |
|      \___ Added whitespaces with possesive quantifier (cannot backtrack)
|
\__ Removed beginning of first capturing group

Finally, if you wanted not using capturing group, and use just matches instead, you may use this regex:

(?<=>)\s*+\K[^<>]+?(?=(?:[\s\r]*<))

It is similar to the previous one. The difference is that is uses \K to forget the current matching string.

You have a new demo here.


问:
Jenkins "Not sending mail to unregistered user"
Jenkins refuses to send error mails to some users.
In the log I found these messages:

```<code>....
Build step 'Maven Goals aufrufen' marked build as failure
Not sending mail to unregistered user user1@example.org
Sending e-mails to: user2@example.org
Finished: FAILURE
</code>```

The user (user1) is listed in the admin people list. He also has an registered email (user1@example.org).

So why is this user called an unregistered user?

When searching for this warning, I find several open JIRA issues such as https://issues.jenkins-ci.org/browse/JENKINS-43178
But these doesn't help me.

Is this a misconfiguration or a jenkins bug?

答:
From the OP it's not clear if they use LDAP, but here is some information that solved it for me and that I haven't found anywhere, including the Jenkins JIRA.

The following suggestion:

-Dhudson.tasks.MailSender.SEND_TO_UNKNOWN_USERS=true

as well as:

Allow sending to unregistered users

and:

Create committer as Jenkins user

did not work for me. The first answer did put me on the track to a solution, though.
It turns out that when using LDAP, Jenkins actually matches against the user name of the git committer. So if the git commit message is:

```<code>Committer: John Doe <John.Doe@company.com>  2019-05-27 19:12:00
</code>```

Jenkins will take "John Doe", convert it to "john.doe" and try to match against LDAP. Now, if your LDAP user name is "john.doe" you're good, but in my case the company standard is "doejohn", which will lead to the dreaded message:

```<code>Not sending mail to unregistered user John.Doe@company.com
</code>```

This message is very misleading since it shows the correct e-mail address instead of mentioning the invented (non-existing) user name. The solution for me was to configure the git user name to "doejohn":

```<code>$ git config --global user.name "doejohn"
</code>```

Body:
Jenkins refuses to send error mails to some users.
In the log I found these messages:

....
Build step 'Maven Goals aufrufen' marked build as failure
Not sending mail to unregistered user user1@example.org
Sending e-mails to: user2@example.org
Finished: FAILURE

The user (user1) is listed in the admin people list. He also has an registered email (user1@example.org).

So why is this user called an unregistered user?

When searching for this warning, I find several open JIRA issues such as https://issues.jenkins-ci.org/browse/JENKINS-43178
But these doesn't help me.

Is this a misconfiguration or a jenkins bug?

Body:
From the OP it's not clear if they use LDAP, but here is some information that solved it for me and that I haven't found anywhere, including the Jenkins JIRA.

The following suggestion:

-Dhudson.tasks.MailSender.SEND_TO_UNKNOWN_USERS=true

as well as:

Allow sending to unregistered users

and:

Create committer as Jenkins user

did not work for me. The first answer did put me on the track to a solution, though.
It turns out that when using LDAP, Jenkins actually matches against the user name of the git committer. So if the git commit message is:

Committer: John Doe <John.Doe@company.com>  2019-05-27 19:12:00

Jenkins will take "John Doe", convert it to "john.doe" and try to match against LDAP. Now, if your LDAP user name is "john.doe" you're good, but in my case the company standard is "doejohn", which will lead to the dreaded message:

Not sending mail to unregistered user John.Doe@company.com

This message is very misleading since it shows the correct e-mail address instead of mentioning the invented (non-existing) user name. The solution for me was to configure the git user name to "doejohn":

$ git config --global user.name "doejohn"


问:
What's the difference between "git log --diff-filter=R" and "git log --find-renames"?
I've learned in a video tutorial about the git command

git log --diff-filter=R --find-renames,

and by reading the docs I came to the conclusion that

git log --diff-filter=R

should yield the same results as

git log --find-renames

and the first combined command could be considered a typo.

Yet when I tried it in one repo, both commands separately yielded the same results, while in another repo only the latter one yielded any results.
Also, I can not find any documentation regarding possible differences between the two.

Can someone please tell me what the difference between these commands is besides the fact that you can add different modifiers to each one?

答:
The difference is really pretty simple:

The --find-renames option turns on the rename-finding machinery, using the default 50%-similar file-matching threshold.  The rename-finding machinery is off by default in rather old versions of Git, and on by default in newer versions of Git, so if you have a newer version of Git (and have not changed the defaults), adding --find-renames to your git diff has no effect at all.1

The --diff-filter= option sets up filters telling Git which files to selectively display after running the internal diff engine.  Selecting R tells Git to display only those files for which a rename was detected.

Hence, if you have an ancient version of Git, you need both options (or see footnote 1) to see only renamed files, but with a modern Git, just the --diff-filter=R option suffices unless the configuration for that repository has rename detection disabled.

1There are also several configuration knobs that you can set with git config or with -c options.  The most relevant here is diff.renames, which can be set to false, true, or either copy or copies.  See the git config documentation for further details.  The default value of diff.rename changed from false to true in Git 2.9.0.


问:
ASP.NET/MVC3 - solution for user-customized reports without developer intervention
Are there any libraries or solutions (third party, open source or commercial) that allow users to create their own reports, which would be accessible from the front-end, without developers' intervention (for most cases?)

Basically, we are using Entity Framework as the ORM. The application will collect stats such as transactions between users, which pages on the site have been visited, and by which user. We have to come up with an interface that allow an administrator to come up with reports which are basically joins between tables. Adding to the difficulty is that the user is able to come up with reports on the fly without messing around with the code.

We would like the user to go through the ORM for those reports, so writing raw SQL statements is out of the question. Is there any ways to let users define their own custom 'views' of a database to generate reports?

答:
How about to let user write his own linq query? Or sql that would be executed with entity framework?

Linq can be written as string and executed also. Look at this nice tutorial. You could make some nice editor yourselves to hide query language from user.


问:
binding to a suspended function in android
I want to bind a button click to a suspended function inside viewmodel.

this is my code:

RegistrationActivityViewModel.kt

```<code>    suspend fun register() {
        if (validateFields()) {
            val result = SourceplusplusApiService.invoke().registerUser(username.value!!, email.value!!, password.value!!).await()
            isRegistrationCompleted.value = getResultValue(result)
        }
    }
</code>```

activity_registration.xml

```<code><Button
          android:text="Register"
          android:onClick="@{()->viewmodel.register()}"
          android:textSize="16sp" />
</code>```

i get a databinding error that says ActivityRegistrationBindingImpl not generated. after searching a lot i realized that when i remove the suspend keyword and comment the code inside, it works fine but it has to be a suspended function.

Does anyone know how to fix it?

答:
You cannot data bind to a suspend function, and IMHO a viewmodel should not be exposing a suspend function in the first place. I recommend:

Step #1: Remove the suspend keyword from register()

Step #2: Rewrite register() to run your code in a suitable coroutine scope, so any suspend functions that it calls are handled properly:

```<code>fun register() {
    viewModelScope.launch(Dispatchers.Main) {
        if (validateFields()) {
            val result = SourceplusplusApiService.invoke().registerUser(username.value!!, email.value!!, password.value!!).await()
            isRegistrationCompleted.value = getResultValue(result)
        }
    }
}
</code>```

Here, I am using the viewModelScope option provided by androidx.lifecycle:lifecycle-viewmodel-ktx version 2.1.0-alpha01 and newer. Alternatively, manage your own coroutine scope. Dispatchers.Main will ensure that any results of that work is available to you on the Android main application thread.

Now, your data binding expression can refer to register(), while you still have a coroutine scope for calling downstream suspend functions.

Body:
I want to bind a button click to a suspended function inside viewmodel.

this is my code:

RegistrationActivityViewModel.kt

    suspend fun register() {
        if (validateFields()) {
            val result = SourceplusplusApiService.invoke().registerUser(username.value!!, email.value!!, password.value!!).await()
            isRegistrationCompleted.value = getResultValue(result)
        }
    }

activity_registration.xml

<Button
          android:text="Register"
          android:onClick="@{()->viewmodel.register()}"
          android:textSize="16sp" />

i get a databinding error that says ActivityRegistrationBindingImpl not generated. after searching a lot i realized that when i remove the suspend keyword and comment the code inside, it works fine but it has to be a suspended function.

Does anyone know how to fix it?

Body:
You cannot data bind to a suspend function, and IMHO a viewmodel should not be exposing a suspend function in the first place. I recommend:

Step #1: Remove the suspend keyword from register()

Step #2: Rewrite register() to run your code in a suitable coroutine scope, so any suspend functions that it calls are handled properly:

fun register() {
    viewModelScope.launch(Dispatchers.Main) {
        if (validateFields()) {
            val result = SourceplusplusApiService.invoke().registerUser(username.value!!, email.value!!, password.value!!).await()
            isRegistrationCompleted.value = getResultValue(result)
        }
    }
}

Here, I am using the viewModelScope option provided by androidx.lifecycle:lifecycle-viewmodel-ktx version 2.1.0-alpha01 and newer. Alternatively, manage your own coroutine scope. Dispatchers.Main will ensure that any results of that work is available to you on the Android main application thread.

Now, your data binding expression can refer to register(), while you still have a coroutine scope for calling downstream suspend functions.


问:
Sails 1.0 cannot access autogenerated associated entity routes
I have an association between Client and Budget as follows:

```<code>//Client.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    name: {
      type: 'string'
    },
    phone: {
      type: 'string',
      unique: true
    },
    email: {
      type: 'string',
      unique: true
    },
    budgets: {
      collection: 'budget',
      via: 'client'
    },
  }
};

// Budget.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    client: {
      model: 'client'
    },
    budgetItems: {
      type: 'json'
    }
  }
};
</code>```

So, POST is working for both entities so I can create both of them, but:

```<code> GET /budget/1
</code>```

returns the budget and the id of the associated client.

```<code> GET /budget/1/client
</code>```

returns the client id without populating(as i've seen in documentation it should be populated).

```<code> GET /client/1
</code>```

returns the client attributes and there is not a field related with budgets.

```<code> GET /client/1/budgets
</code>```

returns 404 NOT FOUND

I'm following this and this official documentation

So what I could be missing?

Is just generating one direction associations, and I've compared with official documentation and third party examples and my code looks fine.

Thanks in advance!

Update:

I still looking for troubles and if I run sails with --silly option it shows there is the following route available:

Binding route ::  get /client/:parentid/budgets POLICY: localize

  Binding route ::  get /client/:parentid/budgets POLICY: isauth

  Binding route ::  get /client/:parentid/budgets BLUEPRINT: populate

but if I try to access returns a 404 Not Found and console shows the following error, thrown by populate.js from Sails core code:

verbo: In populate blueprint action: Specified parent record (1)
  does not have a budgets.

Update2:

Debugging with sails console I've seen the association is generated properly. Given Client.findOne({id: 1}).populate('budgets').then((client)=>{console.log(client)}) print the client attributes and the associated Budgets but still return 404 Not Found when: GET /client/1/budgets

答:
I have created quick demo and it seems working fine for me.

For demo I have used sails version 1.2.2 and sails-disk as database and there is some minor difference in Model attributes as below
Client.js

```<code>module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    phone: {
      type: 'string',
      unique: true,
      required: true
    },
    email: {
      type: 'string',
      unique: true,
      required: true
    },
    budgets: {
      collection: 'Budget', // <<== B is capital here
      via: 'client'
    },
  },
};
</code>```

Budget.js

```<code>module.exports = {
  attributes: {
    client: {
      model: 'Client' // <<== C is capital here
    },
    budgetItems: {
      type: 'json'
    }
  },
};
</code>```

Let me know if this is helpful

Body:
I have an association between Client and Budget as follows:

//Client.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    name: {
      type: 'string'
    },
    phone: {
      type: 'string',
      unique: true
    },
    email: {
      type: 'string',
      unique: true
    },
    budgets: {
      collection: 'budget',
      via: 'client'
    },
  }
};

// Budget.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    client: {
      model: 'client'
    },
    budgetItems: {
      type: 'json'
    }
  }
};

So, POST is working for both entities so I can create both of them, but:

 GET /budget/1

returns the budget and the id of the associated client.

 GET /budget/1/client

returns the client id without populating(as i've seen in documentation it should be populated).

 GET /client/1

returns the client attributes and there is not a field related with budgets.

 GET /client/1/budgets

returns 404 NOT FOUND

I'm following this and this official documentation

So what I could be missing?

Is just generating one direction associations, and I've compared with official documentation and third party examples and my code looks fine.

Thanks in advance!

Update:

I still looking for troubles and if I run sails with --silly option it shows there is the following route available:

Binding route ::  get /client/:parentid/budgets POLICY: localize

  Binding route ::  get /client/:parentid/budgets POLICY: isauth

  Binding route ::  get /client/:parentid/budgets BLUEPRINT: populate

but if I try to access returns a 404 Not Found and console shows the following error, thrown by populate.js from Sails core code:

verbo: In populate blueprint action: Specified parent record (1)
  does not have a budgets.

Update2:

Debugging with sails console I've seen the association is generated properly. Given Client.findOne({id: 1}).populate('budgets').then((client)=>{console.log(client)}) print the client attributes and the associated Budgets but still return 404 Not Found when: GET /client/1/budgets

Body:
I have created quick demo and it seems working fine for me.

For demo I have used sails version 1.2.2 and sails-disk as database and there is some minor difference in Model attributes as below
Client.js

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    phone: {
      type: 'string',
      unique: true,
      required: true
    },
    email: {
      type: 'string',
      unique: true,
      required: true
    },
    budgets: {
      collection: 'Budget', // <<== B is capital here
      via: 'client'
    },
  },
};

Budget.js

module.exports = {
  attributes: {
    client: {
      model: 'Client' // <<== C is capital here
    },
    budgetItems: {
      type: 'json'
    }
  },
};

Let me know if this is helpful


问:
Negate number without using +, * and -
Is it possible to negate a number without using +,* and - operator.
I know it can be done using BigDecimal negate() Function.
Is it possible to do with out using external libraries.

For ex:
int n = 9
Output:
-9

答:
If you are just looking for a util method you can use Math.negateExact():

```<code>int n = Math.negateExact(9);
</code>```

The result will be -9.

Internally Math.negateExact() uses just -:

```<code>public static int negateExact(int a) {
    if (a == Integer.MIN_VALUE) {
        throw new ArithmeticException("integer overflow");
    }
    return -a;
}
</code>```

Title: Negate number without using +, * and -

Body:
If you are just looking for a util method you can use Math.negateExact():

int n = Math.negateExact(9);

The result will be -9.

Internally Math.negateExact() uses just -:

public static int negateExact(int a) {
    if (a == Integer.MIN_VALUE) {
        throw new ArithmeticException("integer overflow");
    }
    return -a;
}


问:
Under sampling or Over Sampling the dataset using Weka
Hi I'm using Weka framework to perform a data mining task. My dataset is highly imbalances. Once class consists of 1463 labels and other consists of 104. If I under sample the higher number of class becomes into 104 and the total number of variables will become 208. I feel like this is an information loss.

What will be the most suitable option to use in such cases.

答:
You could try reweighting using the ClassBalancer filter.

This will keep all your instances, just reweight them.


问:
ember-cli-mirage trying to stub auth0 (external) URL
I am working on a new Ember.js project and using ember-cli-mirage to stub out my requests. The project is going to use ember-simple-auth and Auth0 for user authentication. I began implementing them in my project, but I'm getting a weird error in the console when I try to sign up with my Google account using the Auth0 login modal:

```<code>Your Ember app tried to GET 'https://(my auth0 domain).auth0.com/userinfo',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?
</code>```

(my auth0 domain redacted above)

I have no idea why Mirage would be trying to stub out a request to an external URL. I was reading the Mirage docs and tried using this.passthrough() in my mirage/config.js file so Mirage would make a real request, but that seems to have had no effect (I'm guessing it only explicitly applies to routes within a namespace defined in the config file).

Can anyone help me understand why this is happening and how to stop Mirage from doing it? Thank you!

答: Ember CLI Mirage intercepts all ajax (XMLHttpRequest) and fetch requests by default. You have to whitelist the requests that should be passed through by using server.passthrough() method. (this is server instance in mirage/config.js.) You could use relative and absolute URLs with server.passthrough as well as with all route handlers. So server.passthrough('https://(my auth0 domain).auth0.com/userinfo') should fix your issue.

Body:
I am working on a new Ember.js project and using ember-cli-mirage to stub out my requests. The project is going to use ember-simple-auth and Auth0 for user authentication. I began implementing them in my project, but I'm getting a weird error in the console when I try to sign up with my Google account using the Auth0 login modal:

Your Ember app tried to GET 'https://(my auth0 domain).auth0.com/userinfo',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?

(my auth0 domain redacted above)

I have no idea why Mirage would be trying to stub out a request to an external URL. I was reading the Mirage docs and tried using this.passthrough() in my mirage/config.js file so Mirage would make a real request, but that seems to have had no effect (I'm guessing it only explicitly applies to routes within a namespace defined in the config file).

Can anyone help me understand why this is happening and how to stop Mirage from doing it? Thank you!


问:
spring boot unable to generate tables in mysql database
I am trying to update the data base schema from defiend JpaEntities but spring boot is not able to generate the database tables.
Log file:

application.properties file:

```<code>spring.datasource.url= jdbc:mysql://localhost:3306/banque_db
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto= update
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
</code>```

client entity class:

```<code> @Entity(name="client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
private String name;
private String email;
@OneToMany(mappedBy = "compte")
private Collection<Compte> comptes;
// + getters and setters
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE

    com.Tuto

```<code><artifactId>MaBanque</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MaBanque</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-data-jpa</artifactId>
    </dependency>
    <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>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

答:
First problem:
The application.properties file:

If you set attribute spring.jpa.hibernate.ddl-auto = update, it will not create the schema for you. Instead, it will, you know, update the existing database, which you currently does not have.

The default value for spring.jpa.hibernate.ddl-auto  is create-drop but you are overriding it.

Your application.properties must be in

src/main/resources

folder.

==> you should fix to:

spring.jpa.hibernate.ddl-auto = create - drop

Second problem: The entity class. You should add @Column on top of the attributes, like so:

```<code>`@Entity(name="client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
@Column
private String name;
@Column
private String email;
@OneToMany(mappedBy = "compte")
private Collection<Compte> comptes;
// + getters and setters`
</code>```

Body:
I am trying to update the data base schema from defiend JpaEntities but spring boot is not able to generate the database tables.
Log file:

application.properties file:

spring.datasource.url= jdbc:mysql://localhost:3306/banque_db
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto= update
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

client entity class:

 @Entity(name="client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
private String name;
private String email;
@OneToMany(mappedBy = "compte")
private Collection<Compte> comptes;
// + getters and setters

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE

    com.Tuto

<artifactId>MaBanque</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MaBanque</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-data-jpa</artifactId>
    </dependency>
    <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>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Body:
First problem:
The application.properties file:

If you set attribute spring.jpa.hibernate.ddl-auto = update, it will not create the schema for you. Instead, it will, you know, update the existing database, which you currently does not have.

The default value for spring.jpa.hibernate.ddl-auto  is create-drop but you are overriding it.

Your application.properties must be in

src/main/resources

folder.

==> you should fix to:

spring.jpa.hibernate.ddl-auto = create - drop

Second problem: The entity class. You should add @Column on top of the attributes, like so:

`@Entity(name="client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
@Column
private String name;
@Column
private String email;
@OneToMany(mappedBy = "compte")
private Collection<Compte> comptes;
// + getters and setters`


问:
Changing input text value with Javascript doesn't change display
I'm trying to change the value of a text input field based on user actions.  I'm doing it like this:

```<code>document.getElementById(textFieldID).value = newValue;</code>```

It isn't quite working -- the original text in the field remains on the screen, unchanged.  However, when I submit the form, it behaves as though the value was indeed changed correctly.  (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.)  Anybody have any insights?  Is there something I need to be doing to redraw the input element?

Edit:  Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:

```<code>
<script LANGUAGE="JavaScript" TYPE="text/javascript">
   function changeText(changeSelector)
   {
      var myindex  = document.getElementById(changeSelector+"Recent").selectedIndex;
      var SelValue = document.getElementById(changeSelector+"Recent").options[myindex].value;
      document.getElementById(changeSelector).value = SelValue;
      document.getElementById("historicalText").value = SelValue;
      document.getElementById("historicalTextSelect").value = changeSelector;
   }
</script>

<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">

<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>
</code>```

And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.

Edit 2:  It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses.  (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.)  It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away.  If it doesn't ... should be interesting.

Edit 3:  Yup.  Fscking JSpell.  Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed.  My thanks to everybody who tried to help; +1's all around, wish I could give more.

答: Use div element instead of textfield. I had same problem, my textfield which is changed with another script wasnt get the right value. you can easily use any div element like textfield with some CSS. than you can get the value from div using innerHTML.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to change the value of a text input field based on user actions.  I'm doing it like this:

document.getElementById(textFieldID).value = newValue;

It isn't quite working -- the original text in the field remains on the screen, unchanged.  However, when I submit the form, it behaves as though the value was indeed changed correctly.  (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.)  Anybody have any insights?  Is there something I need to be doing to redraw the input element?

Edit:  Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:

<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">

<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>

And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.

Edit 2:  It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses.  (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.)  It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away.  If it doesn't ... should be interesting.

Edit 3:  Yup.  Fscking JSpell.  Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed.  My thanks to everybody who tried to help; +1's all around, wish I could give more.


问:
Displaying custom local image marker in OSM using OpenLayers
I have followed the tutorial on how to display a custom image as a marker from this article: https://medium.com/attentive-ai/working-with-openlayers-4-part-3-setting-customised-markers-and-images-on-map-da3369a81941

However, when using my own local project structure to reference my png image, it does not get rendered on the map.

Here is my current code:

var aPoint = new ol.geom.Point(ol.proj.fromLonLat([0, 0]))
var aFeature = new ol.Feature({
  geometry: aPoint
})
var aFeatureStyle = new ol.style.Style({
  image: new ol.style.Icon({
    //src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png'
    src: '../../../dott.png'
  })
})
aFeature.setStyle(aFeatureStyle)
var aSource = new ol.source.Vector({
  features: [aFeature]
})
var aLayer = new ol.layer.Vector({
  source: aSource
})

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        aLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([0, 0]),
        zoom: 14
    })
})
```

When using the src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png' variant, the required dot gets displayed, but when using
src: '../../../dott.png' no markers are displayed.

I have definitely specified the right path to my local png file, so I am out of ideas why this code doesn't work.

I am using the Angular framework and running this on a local development server using Node.

答:
That happened to me, I solved it by using

```<code>import imagePath from '../../../dott.png'
</code>```

and than using the imagePath variable instead using the path ../../../dott.png

Body:
I have followed the tutorial on how to display a custom image as a marker from this article: https://medium.com/attentive-ai/working-with-openlayers-4-part-3-setting-customised-markers-and-images-on-map-da3369a81941

However, when using my own local project structure to reference my png image, it does not get rendered on the map.

Here is my current code:

var aPoint = new ol.geom.Point(ol.proj.fromLonLat([0, 0]))
var aFeature = new ol.Feature({
  geometry: aPoint
})
var aFeatureStyle = new ol.style.Style({
  image: new ol.style.Icon({
    //src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png'
    src: '../../../dott.png'
  })
})
aFeature.setStyle(aFeatureStyle)
var aSource = new ol.source.Vector({
  features: [aFeature]
})
var aLayer = new ol.layer.Vector({
  source: aSource
})

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        aLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([0, 0]),
        zoom: 14
    })
})

When using the src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png' variant, the required dot gets displayed, but when using
src: '../../../dott.png' no markers are displayed.

I have definitely specified the right path to my local png file, so I am out of ideas why this code doesn't work.

I am using the Angular framework and running this on a local development server using Node.

Body:
That happened to me, I solved it by using

import imagePath from '../../../dott.png'

and than using the imagePath variable instead using the path ../../../dott.png


问:
trying to get the inner text content of a span element
I'm trying to create a search bar that will allow the user to search an array of items. I'm using a span element as my filter, but for some reason, I can't get the contents of the element to assign to a variable.

It's a pretty straight forward setup.

I grab the contents of the class wrapping the list, then grab each span element. For sanity reasons I console.log the span elements to ensure they are captured (which, they are).

I then attempt to grab the text contents within and assign it to a txtValue variable which I would then proceed to do a comparison check with the filter.

The part where I assign it to a text value is where the bug occurs, it doesn't seem to grab the inner text. Perhaps I'm going about this wrong?

function search() {
  var input, filter, e, content, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  e = document.getElementById("search-list");
  content = e.getElementsByTagName("span");
  console.log(content);
  for (i = 0; i < content.length; i++) {
    if (content) {
      txtValue = content.innerHTML;
      console.log(textValue);
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        content[i].style.display = "";
      } else {
        content[i].style.display = "none";
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="search-bar">
  <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers">
</div>

<div id="search-list">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div></code>```

答:
content is an nodelist and you need to access index to access node

you defined variable as txtValue in console you're using textValue

function search() {
  var input, filter, e, content, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  e = document.getElementById("search-list");
  content = e.getElementsByTagName("span");
  for (i = 0; i < content.length; i++) {
    if (content) {
      txtValue = content[i].innerHTML;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        content[i].style.display = "";
      } else {
        content[i].style.display = "none";
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="search-bar">
  <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers">
</div>

<div id="search-list">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div></code>```

Body:
I'm trying to create a search bar that will allow the user to search an array of items. I'm using a span element as my filter, but for some reason, I can't get the contents of the element to assign to a variable.

It's a pretty straight forward setup.

I grab the contents of the class wrapping the list, then grab each span element. For sanity reasons I console.log the span elements to ensure they are captured (which, they are).

I then attempt to grab the text contents within and assign it to a txtValue variable which I would then proceed to do a comparison check with the filter.

The part where I assign it to a text value is where the bug occurs, it doesn't seem to grab the inner text. Perhaps I'm going about this wrong?

function search() {
  var input, filter, e, content, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  e = document.getElementById("search-list");
  content = e.getElementsByTagName("span");
  console.log(content);
  for (i = 0; i < content.length; i++) {
    if (content) {
      txtValue = content.innerHTML;
      console.log(textValue);
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        content[i].style.display = "";
      } else {
        content[i].style.display = "none";
      }
    }
  }
}

  <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers">

  1
  2
  3
  4
  5

Body:
content is an nodelist and you need to access index to access node

you defined variable as txtValue in console you're using textValue

function search() {
  var input, filter, e, content, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  e = document.getElementById("search-list");
  content = e.getElementsByTagName("span");
  for (i = 0; i < content.length; i++) {
    if (content) {
      txtValue = content[i].innerHTML;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        content[i].style.display = "";
      } else {
        content[i].style.display = "none";
      }
    }
  }
}

<div class="search-bar">
  <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers">
</div>

<div id="search-list">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div>


问:
I don't know why I am having an error message like this CLASS Is Not Abstract And Does Not Override Abstract Method Error
I don't know why I am having an error message like this CLASS Is Not Abstract And Does Not Override Abstract Method Error</p>

```<code>import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
import javax.swing.text.*;

class Editor extends JFrame implements ActionListener{

        JTextArea t;
        JFrame f;
        Editor()
</code>```

答:
From the documentation, ActionListener is an interface that contains the method actionPerformed(ActionEvent e). If you want to implement it, you must either declare your class abstract (can not be instantiated, can have abstract methods without body), or override its method. That is because that's what interfaces do, force the classes implementing them to override their methods.

```<code>class Editor extends JFrame implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}
</code>```

Body:
I don't know why I am having an error message like this CLASS Is Not Abstract And Does Not Override Abstract Method Error

import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
import javax.swing.text.*;

class Editor extends JFrame implements ActionListener{

        JTextArea t;
        JFrame f;
        Editor()

Body:
From the documentation, ActionListener is an interface that contains the method actionPerformed(ActionEvent e). If you want to implement it, you must either declare your class abstract (can not be instantiated, can have abstract methods without body), or override its method. That is because that's what interfaces do, force the classes implementing them to override their methods.

class Editor extends JFrame implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}


问:
Delphi Calculate age of person from TDateEdit component
I have a very simple form with a TDateEdit, TButton and TLabel component.

What is the best way to get the age of someone if the date given is their birthdate? How would someone do this in Delphi from the TDateEdit component and then display the age within the label?

Is there maybe a built in function or something I can use to get the age of someone from their date of birth in the component? I'm looking for the simplest, easiest and best way to do this.

答:
Here is a function to calculate someone's age.

It is distinctly different from the RTL function YearsBetween, as that calculates the number of years between two dates; and is fundamentally not the same as someone's age.

```<code>function GetAge(const BirthDate, CurrentDate: TDateTime): Integer;
var
    y1, m1, d1: Word; //born
    y2, m2, d2: Word; //today
begin
    Result := 0;

    if CurrentDate < BirthDate then
        Exit;

    DecodeDate(BirthDate, y1, m1, d1);
    DecodeDate(CurrentDate, y2, m2, d2);

    //Fudge someone born on the leap-day to Feb 28th of the same year
    //strictly for the purposes of this calculation
    if ( (m1=2) and (d1=29) )
            and
        ( not IsLeapYear(y2) ) then
    begin
        d1 := 28;
    end;

    Result := y2-y1; //rough count of years
    //Take away a year of the month/day is before their birth month/day
    if (m2 < m1) or
            ((m2=m1) and (d2<d1)) then
        Dec(Result);
end;
</code>```

Body:
Here is a function to calculate someone's age.

It is distinctly different from the RTL function YearsBetween, as that calculates the number of years between two dates; and is fundamentally not the same as someone's age.

function GetAge(const BirthDate, CurrentDate: TDateTime): Integer;
var
    y1, m1, d1: Word; //born
    y2, m2, d2: Word; //today
begin
    Result := 0;

    if CurrentDate < BirthDate then
        Exit;

    DecodeDate(BirthDate, y1, m1, d1);
    DecodeDate(CurrentDate, y2, m2, d2);

    //Fudge someone born on the leap-day to Feb 28th of the same year
    //strictly for the purposes of this calculation
    if ( (m1=2) and (d1=29) )
            and
        ( not IsLeapYear(y2) ) then
    begin
        d1 := 28;
    end;

    Result := y2-y1; //rough count of years
    //Take away a year of the month/day is before their birth month/day
    if (m2 < m1) or
            ((m2=m1) and (d2<d1)) then
        Dec(Result);
end;


问:
How to use enums for class functions
I'm working on a project and I have created a class to handle the json response to convert it to modal class and change it back to json request with updated data if needed.

Here in the class I'm getting and saving values from and into dictionary. I need to create an enum for the dictionary keys so that there should be less chance for error for complex key formats.

I even tried using like

```<code>enum Fields {
   case Name
   case Email
}
</code>```

but Fields.Email return Fields object

if I use a protocol of a variable like

```<code>protocol someProtocol {
      var name: String { get }
}

extension someProtocol {
     var name:String {
         return String(describing: self)
     }
}
</code>```

and then extend the enum Fields:someProtocol
then I can use it like Fields.name.name or Fields.email.name

But My client will not approve this I want to create an enum so that I can access the string directly like for name I want key "Name" and I should get it liek "Fields.name" or ".name"

So here I have two objectives

first it that I need to create something that can be accessed through class function

second it should be common so that I can use it with multiple classes

third I can access it with less operators

—

```<code>class PersonService {
    class Update {
        var name = ""
        var email = ""
        var personId = 0

        func createDataFrom(dic:[AnyHashable : Any]) -> Update {
            let update = Update()

            update.name = dictionary["Name"]
            update.email = dictionary["Email"]
            update.personId = dictionary["Id"]

            return update
        }

        func createDataTo() -> [AnyHashable:Any] {
            var ret = [AnyHashable : Any]()

            ret["Name"] = name
            ret["Email"] = email
            ret["Id"] = personId

            return ret
        }
    }
}
</code>```

答:
Something like that?

```<code>enum Fields: String {
   case Name = "Name"
   case Email = "Email"
}
</code>```

```<code>Print(Fields.Name.rawValue)
result: "Name"
</code>```

Or

```<code>struct Constants {
    static let name = "Name"
    static let email = "Email"
}
</code>```

```<code>print(Constants.name)
result: "Name"
</code>```

Title: How to use enums for class functions

Body:
I'm working on a project and I have created a class to handle the json response to convert it to modal class and change it back to json request with updated data if needed.

Here in the class I'm getting and saving values from and into dictionary. I need to create an enum for the dictionary keys so that there should be less chance for error for complex key formats.

I even tried using like

enum Fields {
   case Name
   case Email
}

but Fields.Email return Fields object

if I use a protocol of a variable like

protocol someProtocol {
      var name: String { get }
}

extension someProtocol {
     var name:String {
         return String(describing: self)
     }
}

and then extend the enum Fields:someProtocol
then I can use it like Fields.name.name or Fields.email.name

But My client will not approve this I want to create an enum so that I can access the string directly like for name I want key "Name" and I should get it liek "Fields.name" or ".name"

So here I have two objectives

first it that I need to create something that can be accessed through class function

second it should be common so that I can use it with multiple classes

third I can access it with less operators

—

class PersonService {
    class Update {
        var name = ""
        var email = ""
        var personId = 0

        func createDataFrom(dic:[AnyHashable : Any]) -> Update {
            let update = Update()

            update.name = dictionary["Name"]
            update.email = dictionary["Email"]
            update.personId = dictionary["Id"]

            return update
        }

        func createDataTo() -> [AnyHashable:Any] {
            var ret = [AnyHashable : Any]()

            ret["Name"] = name
            ret["Email"] = email
            ret["Id"] = personId

            return ret
        }
    }
}

Body:
Something like that?

enum Fields: String {
   case Name = "Name"
   case Email = "Email"
}

Print(Fields.Name.rawValue)
result: "Name"

Or

struct Constants {
    static let name = "Name"
    static let email = "Email"
}

print(Constants.name)
result: "Name"


问:
Is it possible to define a function with properties in TypeScript without a type assertion or intermediate?
TypeScript lets you define an interface which is both callable and has properties:

```<code>interface FnWithProps {
    (x: number): number;
    a: string;
    b: string;
}
</code>```

Here's one way to create values assignable to this interface:

```<code>function double(x: number) {
    return x * x;
}
double.a = 'Hello';
double.b = 'Goodbye';

let f: FnWithProps = double;  // ok
</code>```

If double.a or double.b are not set, this triggers an error.

Is it possible to construct such a value directly, without going through an intermediate or using a type assertion?

This isn't valid TypeScript and triggers all sorts of errors:

```<code>let g: FnWithProps = {
    (x: number) => x,
    a: 'Hello',
    b: 'Goodbye',
};
</code>```

答:
I think the intermediate solution is probably the best one as it works well for overloads too, but you can also use Object.assign to get a similar effect :

```<code>let f: FnWithProps = Object.assign(function double(x: number) {
    return x * x;
},{
    a : 'Hello',
    b : 'Goodbye'
});
</code>```

Although this does mean we don't get inference for the function params or the properties.

If this is a common scenario for you, we can build a utility function to get inference for everything:

```<code>interface FnWithProps {
    (x: number): number;
    a: string;
    b: string;
}

function functionWithProps<T extends (...a: any[]) => any>(fn: (...a: Parameters<T>) => ReturnType<T>, props: Pick<T, keyof T>){
    return Object.assign(fn, props);
}

let f = functionWithProps<FnWithProps>(function double(x) { // annotation not necesary
    return x * x;
},{
    a : 'Hello', // helpful intelisense here
    b : 'Goodbye'
});
</code>```

Body:
TypeScript lets you define an interface which is both callable and has properties:

interface FnWithProps {
    (x: number): number;
    a: string;
    b: string;
}

Here's one way to create values assignable to this interface:

function double(x: number) {
    return x * x;
}
double.a = 'Hello';
double.b = 'Goodbye';

let f: FnWithProps = double;  // ok

If double.a or double.b are not set, this triggers an error.

Is it possible to construct such a value directly, without going through an intermediate or using a type assertion?

This isn't valid TypeScript and triggers all sorts of errors:

let g: FnWithProps = {
    (x: number) => x,
    a: 'Hello',
    b: 'Goodbye',
};

Body:
I think the intermediate solution is probably the best one as it works well for overloads too, but you can also use Object.assign to get a similar effect :

let f: FnWithProps = Object.assign(function double(x: number) {
    return x * x;
},{
    a : 'Hello',
    b : 'Goodbye'
});

Although this does mean we don't get inference for the function params or the properties.

If this is a common scenario for you, we can build a utility function to get inference for everything:

interface FnWithProps {
    (x: number): number;
    a: string;
    b: string;
}

function functionWithProps<T extends (...a: any[]) => any>(fn: (...a: Parameters<T>) => ReturnType<T>, props: Pick<T, keyof T>){
    return Object.assign(fn, props);
}

let f = functionWithProps<FnWithProps>(function double(x) { // annotation not necesary
    return x * x;
},{
    a : 'Hello', // helpful intelisense here
    b : 'Goodbye'
});


问:
Log4J - Is there any point in explicitly specifying the class name in the call to LogManager.getLogger()?
I'm working on some legacy code with a lot of code like

```<code>private final Logger logger = LogManager.getLogger(ThisClassName.class);
</code>```

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

```<code>LogManager.getLogger(getClass());
</code>```

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

答:
I would usually use the getClass() version with an instance-variable Logger (you aren't creating another logger instance, merely looking one up).

The reason for this is that in class hierarchies, it can be useful to know what the actual type is of thing you are dealing with, even if logging is occurring from within a method on the superclass.

Normally a simple textual search will give you exactly what log statement is being called anyway, so I haven't found it confusing in practice.

OwnerDisplayName: nc

Body:
I'm working on some legacy code with a lot of code like

private final Logger logger = LogManager.getLogger(ThisClassName.class);

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

LogManager.getLogger(getClass());

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.


问:
Creating views on the fly from array
I need to create a a bunch a views on the fly. I was wondering what would be the best way to go about doing this as ill need to define coordinates, tag, colours of each view.

Would i need to create a multidimensional array and if so how can i do this?

```<code>CGRect viewRect1 = { 80.0, 200.0, 160.0, 100.0 };
UIview *myview1 = [[UIview alloc] initWithFrame:viewRect1];
[myview1 setBackgroundColor:[UIColor darkGrayColor]];
</code>```

答:
You dont really need to store your views in an array unless its just for pure convenience.

You can create a variable amount views using a for loop:

```<code>UIView *myView;
int x=0, y=0;
int viewWidth = 50, viewHeight = 50;
for(int i=0; i<numberOFView; i++){
     myView = [[UIView alloc] initWithFrame:CGRectMake(x,y,viewWidth,viewHeight)];
     //incriment x and y to refelect where you want your next view to be suituated
     myView.tag = i+1;
     [self.view addSubview:myView];
     [myView release];
}
</code>```

Then to access each view in turn and carry out some work you can do the following:

```<code>for (UIView *view in self.view.subviews) {
    switch (view.tag) {
       case 1:
           //do something to the view
           break;
       case 2:
           //do something to the view
           break;
       case 3:
           //do something to the view
           break;
       //and so on...
      default:
           break;
   }
}
</code>```

Title: Creating views on the fly from array

Body:
I need to create a a bunch a views on the fly. I was wondering what would be the best way to go about doing this as ill need to define coordinates, tag, colours of each view.

Would i need to create a multidimensional array and if so how can i do this?

CGRect viewRect1 = { 80.0, 200.0, 160.0, 100.0 };
UIview *myview1 = [[UIview alloc] initWithFrame:viewRect1];
[myview1 setBackgroundColor:[UIColor darkGrayColor]];

Body:
You dont really need to store your views in an array unless its just for pure convenience.

You can create a variable amount views using a for loop:

UIView *myView;
int x=0, y=0;
int viewWidth = 50, viewHeight = 50;
for(int i=0; i<numberOFView; i++){
     myView = [[UIView alloc] initWithFrame:CGRectMake(x,y,viewWidth,viewHeight)];
     //incriment x and y to refelect where you want your next view to be suituated
     myView.tag = i+1;
     [self.view addSubview:myView];
     [myView release];
}

Then to access each view in turn and carry out some work you can do the following:

for (UIView *view in self.view.subviews) {
    switch (view.tag) {
       case 1:
           //do something to the view
           break;
       case 2:
           //do something to the view
           break;
       case 3:
           //do something to the view
           break;
       //and so on...
      default:
           break;
   }
}


问:
Access the image URLs using Scrapy
I am trying to scrape information about houses from this website:https://www.goldenproperty.co.za/property_search_result.aspx?type=allTypes&min_price=0&max_price=1000000000&beds=-1&baths=-1&ids=Cape%20Town.all%20suburbs&status=-1&sqm=-1&land=-1

Specifically, I would want to extract the URL of the images of each property that is listed on the results page.

This part of the code should get the images. However, due to them being available on the child page, I only get GET https://www.goldenproperty.co.za/property/for-sale/tamboerskloof/retail-for-sale_1016735/ rather than the actual URL of the image.

```<code>   def parse(self, response):
        for prop in response.css('div.search_result_panel'):
            link = prop.css('a::attr(href)').get()
            request = scrapy.Request(link, callback = self.get_loc)

            yield {
                .....
                other fields we're extracting
                .....

                'images': request
            }
    def get_loc(self,response):
        div = response.css('div.visible-print')
        pics = div.css('img::attr(src)').getall()
        return pics
</code>```

We want the yield list/dictionary of all the image URLs for each property. Any suggestions?

Thanks in advance.

答:
Since the URLs you need are only available on the item page(child), you need to make a request first, and grab those URLs on get_loc.

If you want to pass info from the search to the item page, you can do it passing your item as meta on request, and then yield the item there with all image URL.

```<code>   def parse(self, response):
        for prop in response.css('div.search_result_panel'):
            link = prop.css('a::attr(href)').get()
            yield scrapy.Request(
                link,
                meta={'item': {'other_fields': other_values}},
                callback=self.get_loc,
            )

    def get_loc(self,response):
        item = response.meta.get('item')
        div = response.css('div.visible-print')
        item['images'] = div.css('img::attr(src)').getall()
        yield item
</code>```

https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request.meta

Title: Access the image URLs using Scrapy

Body:
I am trying to scrape information about houses from this website:https://www.goldenproperty.co.za/property_search_result.aspx?type=allTypes&min_price=0&max_price=1000000000&beds=-1&baths=-1&ids=Cape%20Town.all%20suburbs&status=-1&sqm=-1&land=-1

Specifically, I would want to extract the URL of the images of each property that is listed on the results page.

This part of the code should get the images. However, due to them being available on the child page, I only get GET https://www.goldenproperty.co.za/property/for-sale/tamboerskloof/retail-for-sale_1016735/ rather than the actual URL of the image.

   def parse(self, response):
        for prop in response.css('div.search_result_panel'):
            link = prop.css('a::attr(href)').get()
            request = scrapy.Request(link, callback = self.get_loc)

            yield {
                .....
                other fields we're extracting
                .....

                'images': request
            }
    def get_loc(self,response):
        div = response.css('div.visible-print')
        pics = div.css('img::attr(src)').getall()
        return pics

We want the yield list/dictionary of all the image URLs for each property. Any suggestions?

Thanks in advance.

Body:
Since the URLs you need are only available on the item page(child), you need to make a request first, and grab those URLs on get_loc.

If you want to pass info from the search to the item page, you can do it passing your item as meta on request, and then yield the item there with all image URL.

   def parse(self, response):
        for prop in response.css('div.search_result_panel'):
            link = prop.css('a::attr(href)').get()
            yield scrapy.Request(
                link,
                meta={'item': {'other_fields': other_values}},
                callback=self.get_loc,
            )

    def get_loc(self,response):
        item = response.meta.get('item')
        div = response.css('div.visible-print')
        item['images'] = div.css('img::attr(src)').getall()
        yield item

https://docs.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request.meta


问:
using arrays to query with SELECT with PHP
I'm querying a table that returns id's and I'd like to use these id's within an array to perform another query.

I have the two queries working independently of each other by hard coding the id's into the second query just to be sure that it functions as expected, which it does.

```<code>$query = "SELECT item_id FROM items";

$query = "SELECT * FROM results WHERE results_item_id in (1,2,3,4)";
</code>```

I'd like the return of the second query to include data for all of the id's returned to me from the first query.

答:
Just put the query inside the IN, and add distinct so each item_id you only get in once:

```<code>$query = "SELECT * FROM results WHERE results_item_id in (SELECT distinct item_id FROM items)";
</code>```

Body:
I'm querying a table that returns id's and I'd like to use these id's within an array to perform another query.

I have the two queries working independently of each other by hard coding the id's into the second query just to be sure that it functions as expected, which it does.

$query = "SELECT item_id FROM items";

$query = "SELECT * FROM results WHERE results_item_id in (1,2,3,4)";

I'd like the return of the second query to include data for all of the id's returned to me from the first query.

Body:
Just put the query inside the IN, and add distinct so each item_id you only get in once:

$query = "SELECT * FROM results WHERE results_item_id in (SELECT distinct item_id FROM items)";


问:
Does a thread synchronize with with the previous thread with same id?
In C++11 there is std::this_thread::get_id() I can use to obtain an std::thread::id identifier of my thread. The standard says:

30.3.1.1

An object of type thread::id provides a unique identifier for each thread of execution and a single distinct value for all thread objects
  that do not represent a thread of execution (30.3.1). Each thread of
  execution has an associated thread::id object that is not equal to the
  thread::id object of any other thread of execution and that is not
  equal to the thread::id object of any std::thread object that does not
  represent threads of execution.

thread::id shall be a trivially copyable class (Clause 9). The library may reuse the value of a thread::id of a terminated thread
  that can no longer be joined.

My question is precisely about the case in which a new thread B, has the same id as an old thread A: will the thread B "see changes made by" thread A?

To be more specific consider this scenario:

Thread A does:

```<code>owner.store(std::this_thread::get_id()); //store A's 'id'
...some work...
owner.store(std::thread::id(),std::memory_order_relaxed); // clear
</code>```

Thread B does:

```<code>assert(owner.load(std::memory_order_relaxed) != std::this_thread::get_id());
</code>```

Will this assert hold?

The owner.load in Thread A and last owner.store in Thread B are intentionally "relaxed", as so there is no obvious "synchronize with" relation between the two, other than the one supposed in my question.

答:
My question is precisely about the case in which a new thread B, has
  the same id as an old thread A: will the thread B "see changes made
  by" thread A?

- So, your stipulation is exactly about the scenario when thread A is surely terminated (i.e. cannot be joined any more) and thread B has started, possibly reusing thread A's ID.

in such case (threads A and B are subsequent and not concurrent) the assert will hold - even though its ID might be the same, by the time thread B has started, the owner's storage will be surely emptied (guaranteed by termination of the thread A)

UPDATE: thanks to @Yakk - Adam Nevraumont's comment - it was my overlook of write -> read operations under relaxed order - the above statement is false! i.e. the memory commit in the last operation of thread A will be asynchronous to the read of the thread B and hence the assert might not hold! (sorry for a confusion)

otherwise (threads A and B are concurrent) they would never get the same ID and hence the assert would also hold.

Body:
In C++11 there is std::this_thread::get_id() I can use to obtain an std::thread::id identifier of my thread. The standard says:

30.3.1.1

An object of type thread::id provides a unique identifier for each thread of execution and a single distinct value for all thread objects
  that do not represent a thread of execution (30.3.1). Each thread of
  execution has an associated thread::id object that is not equal to the
  thread::id object of any other thread of execution and that is not
  equal to the thread::id object of any std::thread object that does not
  represent threads of execution.

thread::id shall be a trivially copyable class (Clause 9). The library may reuse the value of a thread::id of a terminated thread
  that can no longer be joined.

My question is precisely about the case in which a new thread B, has the same id as an old thread A: will the thread B "see changes made by" thread A?

To be more specific consider this scenario:

Thread A does:

owner.store(std::this_thread::get_id()); //store A's 'id'
...some work...
owner.store(std::thread::id(),std::memory_order_relaxed); // clear

Thread B does:

assert(owner.load(std::memory_order_relaxed) != std::this_thread::get_id());

Will this assert hold?

The owner.load in Thread A and last owner.store in Thread B are intentionally "relaxed", as so there is no obvious "synchronize with" relation between the two, other than the one supposed in my question.


问:
How to split each digit of a number into different rows
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9
```

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

答:
Then I have to sum all the multiplications. After that there's some
  trivial calculations with the result of the sum, applying some modulus
  and complements, but it's out of the scope of this question.

Why outside the scope off this question, as we love to solve these things.

Query

```<code>SELECT
 11 - (SUM(vector_input.vector_input__summed) % 11)
FROM (

SELECT
 vector.item * input.item AS vector_input__summed

FROM (
 SELECT
  DISTINCT
    SUBSTRING(5432765432, vector_number_generator.number, 1) AS item
    ,  vector_number_generator.number  AS position
FROM (
  SELECT
   @vector_row := @vector_row + 1 AS number
  FROM (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) AS row_1
  CROSS JOIN (
    SELECT @vector_row := 0
  ) AS init_user_params
) AS vector_number_generator

) AS vector
INNER JOIN (
  SELECT
  DISTINCT
       SUBSTRING(2050364496, number_generator.number, 1) AS item
    ,  number_generator.number  AS position
FROM (
  SELECT
   @row := @row + 1 AS number
  FROM (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) row1
  CROSS JOIN (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION  SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) row2
  CROSS JOIN (
    SELECT @row := 0
  ) AS init_user_params
) AS number_generator
) AS input
ON
 vector.position = input.position
) AS vector_input
</code>```

Result

```<code>| 11 - (SUM(vector_input.vector_input__summed) % 11) |
| -------------------------------------------------- |
| 8                                                  |
</code>```

See demo

If modulus 10 should also be used which i assume it should be

((11 - (SUM(vector_input.vector_input__summed) % 11)) % 10) see demo

Body:
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

Body:
Then I have to sum all the multiplications. After that there's some
  trivial calculations with the result of the sum, applying some modulus
  and complements, but it's out of the scope of this question.

Why outside the scope off this question, as we love to solve these things.

Query

SELECT
 11 - (SUM(vector_input.vector_input__summed) % 11)
FROM (

SELECT
 vector.item * input.item AS vector_input__summed

FROM (
 SELECT
  DISTINCT
    SUBSTRING(5432765432, vector_number_generator.number, 1) AS item
    ,  vector_number_generator.number  AS position
FROM (
  SELECT
   @vector_row := @vector_row + 1 AS number
  FROM (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) AS row_1
  CROSS JOIN (
    SELECT @vector_row := 0
  ) AS init_user_params
) AS vector_number_generator

) AS vector
INNER JOIN (
  SELECT
  DISTINCT
       SUBSTRING(2050364496, number_generator.number, 1) AS item
    ,  number_generator.number  AS position
FROM (
  SELECT
   @row := @row + 1 AS number
  FROM (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) row1
  CROSS JOIN (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION  SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) row2
  CROSS JOIN (
    SELECT @row := 0
  ) AS init_user_params
) AS number_generator
) AS input
ON
 vector.position = input.position
) AS vector_input

Result

| 11 - (SUM(vector_input.vector_input__summed) % 11) |
| -------------------------------------------------- |
| 8                                                  |

See demo

If modulus 10 should also be used which i assume it should be

((11 - (SUM(vector_input.vector_input__summed) % 11)) % 10) see demo