问:
Getting a callback in Kotlin in Android
I am a newbie in Kotlin and want to learn Lambda functions. I have learning Android for months now .
 and wanted to integrate both Kotlin and Andriod , so for practicing I am trying to convert Java code to Kotlin. I am facing trouble while getting callbacks. The below code requires a callback which I am not able to achieve.

I haven't mentioned that ReservoirPutCallback interface is coded in Java and is in a read-only mode

Here is mycode(Java),in which I am facing errors :-

```<code>        if(DISK_CACHE_INITIALIZED){
            Reservoir.putAsync(Constants.SCIENTISTS_CACHE_KEY, scientists,
             **new ReservoirPutCallback()** {
                @Override
                public void onSuccess() {
                    //success
                    DISK_CACHE_DIRTY = false;
                }
                @Override
                public void onFailure(Exception e) {
                    Log.e("CAMPOSHA","PUTTING CACHE TO DISK FAILED");
                }
            });
        }
    }

    public static LiveData<List<Scientist>> bindFromDiskCacheAsync(){
        MutableLiveData<List<Scientist>> scientistLiveData=new MutableLiveData<>();
        if(!DISK_CACHE_INITIALIZED){
            return null;
        }
        **Type resultType = new TypeToken<List<Scientist>>() {}.getType()**;
        Reservoir.getAsync(Constants.SCIENTISTS_CACHE_KEY, resultType,
         new ReservoirGetCallback<List<Scientist>>() {
            @Override
            public void onSuccess(List<Scientist> scientists) {
                scientistLiveData.setValue(scientists);
            }
            @Override
            public void onFailure(Exception e) {
                Log.e("CAMPOSHA","ASYNC REFRESH FROM DISK FAILED");
                scientistLiveData.setValue(null);
            }
        });
        return scientistLiveData;
    }
</code>```

答:
Kotlin supports what you're trying to do. You're actually passing a full object as a parameter, not just a callback. If it was a single callback function, you could use a lambda, but this is more like a "callback object".

For that, we use anonymous objects rather than lambdas/functions. This is true for both java and kotlin.

The first callback will look like:

```<code>Reservoir.putAsync(Constants.SCIENTISTS_CACHE_KEY, scientists,
    object : ReservoirPutCallback {

        override fun onSuccess() {
            //success
            DISK_CACHE_DIRTY = false
        }

        override fun onFailure(e: Exception) {
            Log.e("CAMPOSHA","PUTTING CACHE TO DISK FAILED")
        }
    }
)
</code>```

The second is roughly the same thing.

Title: Getting a callback in Kotlin in Android

Body:
I am a newbie in Kotlin and want to learn Lambda functions. I have learning Android for months now .
 and wanted to integrate both Kotlin and Andriod , so for practicing I am trying to convert Java code to Kotlin. I am facing trouble while getting callbacks. The below code requires a callback which I am not able to achieve.

I haven't mentioned that ReservoirPutCallback interface is coded in Java and is in a read-only mode

Here is mycode(Java),in which I am facing errors :-

        if(DISK_CACHE_INITIALIZED){
            Reservoir.putAsync(Constants.SCIENTISTS_CACHE_KEY, scientists,
             **new ReservoirPutCallback()** {
                @Override
                public void onSuccess() {
                    //success
                    DISK_CACHE_DIRTY = false;
                }
                @Override
                public void onFailure(Exception e) {
                    Log.e("CAMPOSHA","PUTTING CACHE TO DISK FAILED");
                }
            });
        }
    }

    public static LiveData<List<Scientist>> bindFromDiskCacheAsync(){
        MutableLiveData<List<Scientist>> scientistLiveData=new MutableLiveData<>();
        if(!DISK_CACHE_INITIALIZED){
            return null;
        }
        **Type resultType = new TypeToken<List<Scientist>>() {}.getType()**;
        Reservoir.getAsync(Constants.SCIENTISTS_CACHE_KEY, resultType,
         new ReservoirGetCallback<List<Scientist>>() {
            @Override
            public void onSuccess(List<Scientist> scientists) {
                scientistLiveData.setValue(scientists);
            }
            @Override
            public void onFailure(Exception e) {
                Log.e("CAMPOSHA","ASYNC REFRESH FROM DISK FAILED");
                scientistLiveData.setValue(null);
            }
        });
        return scientistLiveData;
    }

Body:
Kotlin supports what you're trying to do. You're actually passing a full object as a parameter, not just a callback. If it was a single callback function, you could use a lambda, but this is more like a "callback object".

For that, we use anonymous objects rather than lambdas/functions. This is true for both java and kotlin.

The first callback will look like:

Reservoir.putAsync(Constants.SCIENTISTS_CACHE_KEY, scientists,
    object : ReservoirPutCallback {

        override fun onSuccess() {
            //success
            DISK_CACHE_DIRTY = false
        }

        override fun onFailure(e: Exception) {
            Log.e("CAMPOSHA","PUTTING CACHE TO DISK FAILED")
        }
    }
)

The second is roughly the same thing.


来源: stackexchange

问:
Correct the correlation names in my SQL query
I have the following SQL Query where I want to extract the count of each item and its name e.g. "FillingOption" from my SQL database.

I keep getting the following error message

Msg 1013, Level 16, State 1, Line 13
  The objects "school_to_classroom_teacher" and "school_to_classroom_teacher" in the FROM clause have the same exposed names. Use correlation names to distinguish them.

The query is as follows:

```<code>SELECT
    COUNT(*) AS count,
    Monday_Sandwich_Roll_Filling.FillingOption
FROM
    #tempCustomer
    INNER JOIN Monday_Sandwich_Roll_Filling
        ON #tempCustomer.LunchMon=Monday_Sandwich_Roll_Filling.FillingOption
    INNER JOIN school_to_classroom_teacher
        ON #tempCustomer.teacherID= school_to_classroom_teacher.teacherID
    INNER JOIN [teacherClassroom Table]
        ON #tempCustomer.teacherID= [teacherClassroom Table].teacherID
    inner join school_to_classroom_teacher
        on [teacherClassroom Table].teacherID=school_to_classroom_teacher.teacherID
    inner join SchoolTable
        on SchoolTable.SchoolID
WHERE
    (SchoolTable.mondayOn = 1)
    AND school_to_classroom_teacher.schoolid = 1
    AND([teacherClassroom Table].Available = 1)```
```

Apologies for the messy query but its the "SchoolTable.SchoolID" beside the WHERE clause and the "school_to_classroom_teacher" parts of the query it doesn't like.

I've tried declaring SchoolTable.SchoolID AS TEST but that doesn't work.

Anyone have any ideas.

答:
So you basically want to do this (I removed duplicate/superfluous join):

```<code>SELECT
    COUNT(*) AS count,
    Monday_Sandwich_Roll_Filling.FillingOption
FROM
    #tempCustomer
    INNER JOIN Monday_Sandwich_Roll_Filling
        ON #tempCustomer.LunchMon=Monday_Sandwich_Roll_Filling.FillingOption
    INNER JOIN school_to_classroom_teacher
        ON #tempCustomer.teacherID= school_to_classroom_teacher.teacherID
    INNER JOIN [teacherClassroom Table]
        ON #tempCustomer.teacherID= [teacherClassroom Table].teacherID
        and [teacherClassroom Table].teacherID=school_to_classroom_teacher.teacherID
    inner join SchoolTable
        on SchoolTable.SchoolID
WHERE
    (SchoolTable.mondayOn = 1)
    AND school_to_classroom_teacher.schoolid = 1
    AND([teacherClassroom Table].Available = 1)
</code>```

But you're also missing a join condition on your last join inner join SchoolTable
            on SchoolTable.SchoolID.....?

ContentLicense: CC BY-SA 4.0

Body:
I have the following SQL Query where I want to extract the count of each item and its name e.g. "FillingOption" from my SQL database.

I keep getting the following error message

Msg 1013, Level 16, State 1, Line 13
  The objects "school_to_classroom_teacher" and "school_to_classroom_teacher" in the FROM clause have the same exposed names. Use correlation names to distinguish them.

The query is as follows:

SELECT
    COUNT(*) AS count,
    Monday_Sandwich_Roll_Filling.FillingOption
FROM
    #tempCustomer
    INNER JOIN Monday_Sandwich_Roll_Filling
        ON #tempCustomer.LunchMon=Monday_Sandwich_Roll_Filling.FillingOption
    INNER JOIN school_to_classroom_teacher
        ON #tempCustomer.teacherID= school_to_classroom_teacher.teacherID
    INNER JOIN [teacherClassroom Table]
        ON #tempCustomer.teacherID= [teacherClassroom Table].teacherID
    inner join school_to_classroom_teacher
        on [teacherClassroom Table].teacherID=school_to_classroom_teacher.teacherID
    inner join SchoolTable
        on SchoolTable.SchoolID
WHERE
    (SchoolTable.mondayOn = 1)
    AND school_to_classroom_teacher.schoolid = 1
    AND([teacherClassroom Table].Available = 1)```

Apologies for the messy query but its the "SchoolTable.SchoolID" beside the WHERE clause and the "school_to_classroom_teacher" parts of the query it doesn't like.

I've tried declaring SchoolTable.SchoolID AS TEST but that doesn't work.

Anyone have any ideas.

Body:
So you basically want to do this (I removed duplicate/superfluous join):

SELECT
    COUNT(*) AS count,
    Monday_Sandwich_Roll_Filling.FillingOption
FROM
    #tempCustomer
    INNER JOIN Monday_Sandwich_Roll_Filling
        ON #tempCustomer.LunchMon=Monday_Sandwich_Roll_Filling.FillingOption
    INNER JOIN school_to_classroom_teacher
        ON #tempCustomer.teacherID= school_to_classroom_teacher.teacherID
    INNER JOIN [teacherClassroom Table]
        ON #tempCustomer.teacherID= [teacherClassroom Table].teacherID
        and [teacherClassroom Table].teacherID=school_to_classroom_teacher.teacherID
    inner join SchoolTable
        on SchoolTable.SchoolID
WHERE
    (SchoolTable.mondayOn = 1)
    AND school_to_classroom_teacher.schoolid = 1
    AND([teacherClassroom Table].Available = 1)

But you're also missing a join condition on your last join inner join SchoolTable
            on SchoolTable.SchoolID.....?


问:
varnish / docker-compose custom port and cache size
I'm trying to figure out how to pass custom port and cache size and vcl file in docker-compose.yml to varnish (I'm using the official varnish image https://hub.docker.com/_/varnish )

I Tried using environment variables by adding the following lines into my docker-compose.yml but it seems that they are not taken into consideration

```<code>    environment:
      - VARNISH_CONFIG="/etc/varnish/custom.vcl"
      - CACHE_SIZE=512m
      - VARNISH_PORT=8080
</code>```

Any clue on how to pass these params to a varnish container ?

答:
The official Varnish Docker image is quite basic at this point. As you concluded in your second post, you can use our the image as the basis, and then customize the behavior in your own Dockerfile.

However, for Varnish Software, it's an iterative process, so we'll gradually add features to the image. In the end, you'll be able to configure most parameters through environment variables in your docker-compose.yml file.

We're working on it, thanks for your patience.

Body:
I'm trying to figure out how to pass custom port and cache size and vcl file in docker-compose.yml to varnish (I'm using the official varnish image https://hub.docker.com/_/varnish )

I Tried using environment variables by adding the following lines into my docker-compose.yml but it seems that they are not taken into consideration

    environment:
      - VARNISH_CONFIG="/etc/varnish/custom.vcl"
      - CACHE_SIZE=512m
      - VARNISH_PORT=8080

Any clue on how to pass these params to a varnish container ?


问:
Gatsby Not Resolving GraphQL Image Address
My project is based on the gatsby-creative starter.  I am trying to add an Open Graph image meta property.  Unfortunately, the address of the image in the source folder is not being translated into a proper content path.  Here is what I did...

I started by adding a "url" and "image" properties to siteMetaData:

```<code>  siteMetadata: {
    title: `A Web Site`,
    description: `Yes, this is a web site.`,
    author: `Brent Arias`,
    url: `https://website.com`,
    image: `/images/snape.jpg`
  },
</code>```

So far I'm doing the same thing as the online documentation.  However, those instructions have a comment which states the above "image" property contains the Path to your image you placed in the 'static' folder.  Huh?  I don't believe I'm supposed to "place an image in the static folder"...I think that is Gatsby's job.  But moving along...

Starting from this original seo.js file, I added the same "url" and "image" properties to the graphQL query:

```<code>  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
            description
            author
            url
            image
          }
        }
      }
    `
  )
</code>```

Seemingly, so far so good.  Finally, in the same seo.js file, I added an entry for the image itself:

```<code>        {
          property: `og:type`,
          content: `website`,
        },
        {
          property: `og:url`,
          content: site.siteMetadata.url,
        },
        {
          property: `og:image`,
          content: `${site.siteMetadata.url}${site.siteMetadata.image}`
        },
</code>```

When the page renders, the meta tag contains the useless address https://website.com/images/snape.jpg.

Yes the online documentation is not identical to this approach, but it seems to be the equivalent.  I don't see why the address isn't being resolved to the "static" folder where the image should be found.

As a work-around hack, instead I added to the seo.js file the following:

import socialBanner from '../images/snape.jpg'

When I place that socialBanner into the "content" of that same "og:image" property, then it works as expected and resolves to: https://website.com/static/snape-119744a51329473845d08af3df4b5290.jpg.

I don't want that hack. What do I need to change to properly make use of Gatsby tools (StaticQuery, Helmet, etc) to handle this image and address?

答:
The static folder being referenced by the Gatsby documentation is at the root of your project. Here's the documentation for the static folder and it's behavior in Gatsby.

If you want to use the approach shown in the SEO example documentation, you'll need to add your OpenGraph image to this folder, not to public/static, which is a folder that Gatsby uses for files that it generates.

Adding assets outside of the module system

You can create a folder named static at the root of your project. Every file you put into that folder will be copied into the public folder. E.g. if you add a file named sun.jpg to the static folder, it’ll be copied to public/sun.jpg

Body:
My project is based on the gatsby-creative starter.  I am trying to add an Open Graph image meta property.  Unfortunately, the address of the image in the source folder is not being translated into a proper content path.  Here is what I did...

I started by adding a "url" and "image" properties to siteMetaData:

  siteMetadata: {
    title: `A Web Site`,
    description: `Yes, this is a web site.`,
    author: `Brent Arias`,
    url: `https://website.com`,
    image: `/images/snape.jpg`
  },

So far I'm doing the same thing as the online documentation.  However, those instructions have a comment which states the above "image" property contains the Path to your image you placed in the 'static' folder.  Huh?  I don't believe I'm supposed to "place an image in the static folder"...I think that is Gatsby's job.  But moving along...

Starting from this original seo.js file, I added the same "url" and "image" properties to the graphQL query:

  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
            description
            author
            url
            image
          }
        }
      }
    `
  )

Seemingly, so far so good.  Finally, in the same seo.js file, I added an entry for the image itself:

        {
          property: `og:type`,
          content: `website`,
        },
        {
          property: `og:url`,
          content: site.siteMetadata.url,
        },
        {
          property: `og:image`,
          content: `${site.siteMetadata.url}${site.siteMetadata.image}`
        },

When the page renders, the meta tag contains the useless address https://website.com/images/snape.jpg.

Yes the online documentation is not identical to this approach, but it seems to be the equivalent.  I don't see why the address isn't being resolved to the "static" folder where the image should be found.

As a work-around hack, instead I added to the seo.js file the following:

import socialBanner from '../images/snape.jpg'

When I place that socialBanner into the "content" of that same "og:image" property, then it works as expected and resolves to: https://website.com/static/snape-119744a51329473845d08af3df4b5290.jpg.

I don't want that hack. What do I need to change to properly make use of Gatsby tools (StaticQuery, Helmet, etc) to handle this image and address?


问:
Kafka Stream to divide job & joining them
I have requirement where I get record into topic. With single record I create n different jobs(which should get distributed). Once I successfully process n jobs I need push successfully processed record. Does it qualify for Kafka streams? Basically what I am looking at is , I have video (lets say 20min duration) which needs to be transcoded. I will create 4 tasks(each 5 min) , each worker will process these 4 tasks individually. Once all 4 tasks are completed I need to stitch it back together. I am trying to see if KafaStreams is possible fit to distribute the jobs & then join.</p>

答:
I probably wouldn't recommend using kafka streams for the data itself as it is not meant to deal with such large messages like videos are. But you can use it as a messaging system, saying:

First event comes, hey I got a new video to process

You trigger the software from within your stream

After completion, the software writes another event into a kafka topic to say, it has finished it's job

The kafka streams application could then process this event to trigger the other software to do it's job

Hope it helps.


问:
CTE vs View Performance in SQL Server
Which one is faster :

query from a cte

query from a view

(in Complex Queries). I have a complex query and i have another complex query from the first one.Is it faster to create a view for the first complex query and query from the view or use cte?

答: A view is a permanent object and the results can be indexed, while a CTE is temporary and created only when used so less flexible.  It will be more efficient to break apart your complex query into indexed views than into CTE's.  It will be most efficient to ensure all of the tables are properly indexed, which will probably do more for performance than worrying about views vs. CTE's.</p>

ContentLicense: CC BY-SA 3.0

Title: CTE vs View Performance in SQL Server


问:
Horizontal lines with LineCollection in matplotlib?
How do I add, or create horizontal lines with LineCollection in matplotlib? I am trying to make an animation faster, and don't want to go over old ground, but basically I am trying to avoid using axhline in a for loop to construct an array of lines. Hence it was recommended that I try LineCollection. But so far I can only get to plot a series.

```<code>import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9]
y = [42,13,24,14,74,45,22,44,77]

lc = LineCollection(zip(x,y),color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,10)
a.set_ylim(0,100)
plt.show()
</code>```

And if I add the coordinates explicitly, for example:

```<code>x = [(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9)]
y = [(42,42),(13,13),(24,24),(14,14),(74,74),(45,45),(22,22),(44,44),(77,77)]
</code>```

I get the following plot?

How is that even possible?

答:
Here you go:

```<code>import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

# set x coordinates range
N = 10
x = np.arange(1, N, 1)

# create set od data for lines
number_of_lines = 6
base_array = np.ones(N-1)
lines_list = [base_array + i for i in range(number_of_lines)]

# set plot limits
fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(lines_list)-1, np.max(lines_list)+1)

# load sequences of aray pairs (x,y)
line_segments = LineCollection([np.column_stack([x, y]) for y in lines_list], linestyles='solid')
line_segments.set_array(x)
ax.add_collection(line_segments)
plt.show()
</code>```

Output:

Body:
How do I add, or create horizontal lines with LineCollection in matplotlib? I am trying to make an animation faster, and don't want to go over old ground, but basically I am trying to avoid using axhline in a for loop to construct an array of lines. Hence it was recommended that I try LineCollection. But so far I can only get to plot a series.

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9]
y = [42,13,24,14,74,45,22,44,77]

lc = LineCollection(zip(x,y),color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,10)
a.set_ylim(0,100)
plt.show()

And if I add the coordinates explicitly, for example:

x = [(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9)]
y = [(42,42),(13,13),(24,24),(14,14),(74,74),(45,45),(22,22),(44,44),(77,77)]

I get the following plot?

How is that even possible?

Body:
Here you go:

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

# set x coordinates range
N = 10
x = np.arange(1, N, 1)

# create set od data for lines
number_of_lines = 6
base_array = np.ones(N-1)
lines_list = [base_array + i for i in range(number_of_lines)]

# set plot limits
fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(lines_list)-1, np.max(lines_list)+1)

# load sequences of aray pairs (x,y)
line_segments = LineCollection([np.column_stack([x, y]) for y in lines_list], linestyles='solid')
line_segments.set_array(x)
ax.add_collection(line_segments)
plt.show()

Output:


问:
Can't Connect in R to MySQL Server through SSH

Background

I'm trying to pull data from a cloud MySQL Server. I just moved the database from a shared server to a dedicated cloud server. Everything works fine on the old location. The new location requires an SSH tunnel.

Research/Info:

All I've found that's similar is this SO article. It didn't really apply, as I never used localhost.

I can successfully connect using the same credentials in both Sequel Pro and MySQL Workbench, but I can't get the R script to play ball.

I can connect to mysql in the command line.

I do not have mysql installed locally. (Unless it ships with High Sierra; I have no idea. In any case, if there's a local MySQL instance, it's not running.)

Code:

Here's what's failing:

```<code>con <- dbConnect(RMariaDB::MariaDB(),
                 user = 'soundings_app',
                 password = keyringr::decrypt_kc_pw("Soundings_app"),
                 host = '127.0.0.1',
                 port = 3306,
                 dbname='UFO')
</code>```

I also tried using the actual password as a string, and got the same error.

Error message

```<code>Error in connection_create(host, username, password, dbname, as.integer(port),  :
  Failed to connect: Can't connect to MySQL server on '127.0.0.1' (57)
</code>```

My Only Guess

The only thing I can think of is that SequelPro & Workbench both had a place to enter the location of my private key (~/.ssh).

Can you explain what I'm doing wrong?

UPDATE

I added the host to my ./ssh/config file as follows:

```<code>Host XXX.XXX.130.0
  LocalForward 3306 localhost:3306
</code>```

That caused my other connections to fail, so I removed it. But Sequel Pro gave me the following info when I tried to connect with ~/.ssh/config still in place:

```<code>Used command:  /usr/bin/ssh -v -N -S none -o ControlMaster=no -o ExitOnForwardFailure=yes -o ConnectTimeout=10 -o NumberOfPasswordPrompts=3 -i /Users/steves2018air/.ssh/id_rsa -o TCPKeepAlive=no -o ServerAliveInterval=60 -o ServerAliveCountMax=1 ubuntu@XXX.XXX.130.0 -L 49700:127.0.0.1:3306

OpenSSH_7.6p1, LibreSSL 2.6.2
debug1: Reading configuration data /Users/steves2018air/.ssh/config
debug1: /Users/steves2018air/.ssh/config line 1: Applying options for XXX.XXX.130.0
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: Control socket " none" does not exist
debug1: Connecting to XXX.XXX.130.0 [XXX.XXX.130.0] port 22.
debug1: fd 3 clearing O_NONBLOCK
debug1: Connection established.
debug1: identity file /Users/steves2018air/.ssh/id_rsa type 0
debug1: key_load_public: No such file or directory
debug1: identity file /Users/steves2018air/.ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.4
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to XXX.XXX.130.0:22 as 'ubuntu'
</code>```

UPDATE II

On a whim, I tried changing host from '127.0.0.1' to 'localhost', just to see what would happen, and if that might shed any light. Slightly different error:

```<code>Error in connection_create(host, username, password, dbname, as.integer(port),  :
  Failed to connect: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
</code>```

Still no solution or explanation — can you help?

答:
Steve, thanks for this - it worked perfectly form me - after some minor changes.

Mine was saved in the /etc/mysql/mariadb.cnf file.

```<code>con <- dbConnect(RMariaDB::MariaDB(),
user = "yourusername",
password = "yourpassword",
groups = "destination",
default.file = "/etc/mysql/mariadb.cnf",
host = '127.0.0.1',
port = 3308,
dbname="yourdb_name")
</code>```

Body:
Background

I'm trying to pull data from a cloud MySQL Server. I just moved the database from a shared server to a dedicated cloud server. Everything works fine on the old location. The new location requires an SSH tunnel.

Research/Info:

All I've found that's similar is this SO article. It didn't really apply, as I never used localhost.

I can successfully connect using the same credentials in both Sequel Pro and MySQL Workbench, but I can't get the R script to play ball.

I can connect to mysql in the command line.

I do not have mysql installed locally. (Unless it ships with High Sierra; I have no idea. In any case, if there's a local MySQL instance, it's not running.)

Code:

Here's what's failing:

con <- dbConnect(RMariaDB::MariaDB(),
                 user = 'soundings_app',
                 password = keyringr::decrypt_kc_pw("Soundings_app"),
                 host = '127.0.0.1',
                 port = 3306,
                 dbname='UFO')

I also tried using the actual password as a string, and got the same error.

Error message

Error in connection_create(host, username, password, dbname, as.integer(port),  :
  Failed to connect: Can't connect to MySQL server on '127.0.0.1' (57)

My Only Guess

The only thing I can think of is that SequelPro & Workbench both had a place to enter the location of my private key (~/.ssh).

Can you explain what I'm doing wrong?

UPDATE

I added the host to my ./ssh/config file as follows:

Host XXX.XXX.130.0
  LocalForward 3306 localhost:3306

That caused my other connections to fail, so I removed it. But Sequel Pro gave me the following info when I tried to connect with ~/.ssh/config still in place:

Used command:  /usr/bin/ssh -v -N -S none -o ControlMaster=no -o ExitOnForwardFailure=yes -o ConnectTimeout=10 -o NumberOfPasswordPrompts=3 -i /Users/steves2018air/.ssh/id_rsa -o TCPKeepAlive=no -o ServerAliveInterval=60 -o ServerAliveCountMax=1 ubuntu@XXX.XXX.130.0 -L 49700:127.0.0.1:3306

OpenSSH_7.6p1, LibreSSL 2.6.2
debug1: Reading configuration data /Users/steves2018air/.ssh/config
debug1: /Users/steves2018air/.ssh/config line 1: Applying options for XXX.XXX.130.0
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: Control socket " none" does not exist
debug1: Connecting to XXX.XXX.130.0 [XXX.XXX.130.0] port 22.
debug1: fd 3 clearing O_NONBLOCK
debug1: Connection established.
debug1: identity file /Users/steves2018air/.ssh/id_rsa type 0
debug1: key_load_public: No such file or directory
debug1: identity file /Users/steves2018air/.ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.4
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to XXX.XXX.130.0:22 as 'ubuntu'

UPDATE II

On a whim, I tried changing host from '127.0.0.1' to 'localhost', just to see what would happen, and if that might shed any light. Slightly different error:

Error in connection_create(host, username, password, dbname, as.integer(port),  :
  Failed to connect: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Still no solution or explanation — can you help?

Body:
Steve, thanks for this - it worked perfectly form me - after some minor changes.

Mine was saved in the /etc/mysql/mariadb.cnf file.

con <- dbConnect(RMariaDB::MariaDB(),
user = "yourusername",
password = "yourpassword",
groups = "destination",
default.file = "/etc/mysql/mariadb.cnf",
host = '127.0.0.1',
port = 3308,
dbname="yourdb_name")


问:
Create password protected Samba storage pool
```<code><pool type="netfs">
  <name>virtimages</name>
  <source>
    <host name="0.0.0.0"/>
    <dir path="/var/lib/virt/images"/>
    <format type='cifs'/>
  </source>
  <target>
    <path>/var/lib/virt/images</path>
  </target>
</pool>
</code>```

<p>The above libvirt XML configuration can be used to create a Samba storage pool but how do I create a password protected Samba storage pool? </p>

答:
You have to add an auth section inside your source, for example:</p>

```<code>  <name>YourStorage</name>
  <source>
    <host name="storage.example.com" />
    <dir path="/backup" />
    <format type="cifs" />
    <auth type='chap' username='SomeSecretUsername'>
      <secret usage='SomeSecretPass'/>
    </auth>
  </source>
  <target>
    <path>/mnt/storage</path>
  </target>
</pool>```

See: https://libvirt.org/formatstorage.html#StoragePoolSource
</code>```

Body:
<pool type="netfs">
  <name>virtimages</name>
  <source>
    <host name="0.0.0.0"/>
    <dir path="/var/lib/virt/images"/>
    <format type='cifs'/>
  </source>
  <target>
    <path>/var/lib/virt/images</path>
  </target>
</pool>

The above libvirt XML configuration can be used to create a Samba storage pool but how do I create a password protected Samba storage pool?

Body:
You have to add an auth section inside your source, for example:

  <name>YourStorage</name>
  <source>
    <host name="storage.example.com" />
    <dir path="/backup" />
    <format type="cifs" />
    <auth type='chap' username='SomeSecretUsername'>
      <secret usage='SomeSecretPass'/>
    </auth>
  </source>
  <target>
    <path>/mnt/storage</path>
  </target>
</pool>```

See: https://libvirt.org/formatstorage.html#StoragePoolSource


问:
How to do "late" string interpolation in Ruby
```<code>>> string = '#{var}'
=> "\#{var}"

>> proc = Proc.new { |var| string }
=> #<Proc:0xb717a8c4@(pry):6>

>> proc.call(123)
=> "\#{var}"
</code>```

Not really what I want. Double quotes around string result in the obvious undefined local variable.

答:
To clarify, those looking for the answer to this question's title (how to do late string interpolation) should understand that there is no such thing as late string interpolation.

The poster of this question didn't actually care about string interpolation, per se, just formatting.  For those that also don't care about the distinction between string interpolation and string formatting in Ruby, many of the answers here are fine.

If you don't know whether or not you care, there are plenty of responses to stackoverflow questions that explain the nuanced differences -- here's one more explanation:

In general, string interpolation is compile-time syntactic sugar: the format string is "compiled" exactly once (when generating byte code).  With string formatting, the format string is re-parsed on every invocation (see Kernel::sprintf).

To see this, consider this program:

```<code>x=1
s="#{x}"
</code>```

The RubyVM compiles it to bytecode that includes a hard reference to x (see instruction 0005):

```<code>$ ruby --dump=insns <<EXAMPLE
x=1
s="#{x}"
EXAMPLE
== disasm: #<ISeq:<main>@-:1 (1,0)-(2,8)> (catch: FALSE)
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] x@0        [ 1] s@1
0000 putobject_INT2FIX_1_                                             (   1)[Li]
0001 setlocal_WC_0                x@0
0003 putobject                    ""                                  (   2)[Li]
0005 getlocal_WC_0                x@0
0007 dup
0008 checktype                    T_STRING
0010 branchif                     17
0012 dup
0013 opt_send_without_block       <callinfo!mid:to_s, argc:0, FCALL|ARGS_SIMPLE>, <callcache>
0016 tostring
0017 concatstrings                2
0019 dup
0020 setlocal_WC_0                s@1
0022 leave
</code>```

Note that the interpolated string does not appear, as it has been compiled to one call to x.to_s (instruction 0013) and one to the concatstrings VM instruction (instruction 0017).

On the other hand, a solution like:

```<code>x=1
s="%{foo}" % {foo: x}
</code>```

Will, on every invocation, push a format string onto the stack (instruction 0003) and invoke String#% (instruction 0007) to re-parse it, essentially triggering the same format-parsing code described in the Kernel::sprintf documentation.

```<code>$ ruby --dump=insns <<EXAMPLE
> x=1
> s="%{foo}" % {foo: x}
> EXAMPLE
== disasm: #<ISeq:<main>@-:1 (1,0)-(2,21)> (catch: FALSE)
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] x@0        [ 1] s@1
0000 putobject_INT2FIX_1_                                             (   1)[Li]
0001 setlocal_WC_0                x@0
0003 putstring                    "%{foo}"                            (   2)[Li]
0005 getlocal_WC_0                x@0
0007 opt_send_without_block       <callinfo!mid:%, argc:1, kw:[foo], KWARG>, <callcache>
0010 dup
0011 setlocal_WC_0                s@1
0013 leave
</code>```

Most use cases won't care about this distinction, but if you came to this question because you do, there you go.

Body:
>> string = '#{var}'
=> "\#{var}"

>> proc = Proc.new { |var| string }
=> #<Proc:0xb717a8c4@(pry):6>

>> proc.call(123)
=> "\#{var}"

Not really what I want. Double quotes around string result in the obvious undefined local variable.

Body:
To clarify, those looking for the answer to this question's title (how to do late string interpolation) should understand that there is no such thing as late string interpolation.

The poster of this question didn't actually care about string interpolation, per se, just formatting.  For those that also don't care about the distinction between string interpolation and string formatting in Ruby, many of the answers here are fine.

If you don't know whether or not you care, there are plenty of responses to stackoverflow questions that explain the nuanced differences -- here's one more explanation:

In general, string interpolation is compile-time syntactic sugar: the format string is "compiled" exactly once (when generating byte code).  With string formatting, the format string is re-parsed on every invocation (see Kernel::sprintf).

To see this, consider this program:

x=1
s="#{x}"

The RubyVM compiles it to bytecode that includes a hard reference to x (see instruction 0005):

$ ruby --dump=insns <<EXAMPLE
x=1
s="#{x}"
EXAMPLE
== disasm: #<ISeq:<main>@-:1 (1,0)-(2,8)> (catch: FALSE)
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] x@0        [ 1] s@1
0000 putobject_INT2FIX_1_                                             (   1)[Li]
0001 setlocal_WC_0                x@0
0003 putobject                    ""                                  (   2)[Li]
0005 getlocal_WC_0                x@0
0007 dup
0008 checktype                    T_STRING
0010 branchif                     17
0012 dup
0013 opt_send_without_block       <callinfo!mid:to_s, argc:0, FCALL|ARGS_SIMPLE>, <callcache>
0016 tostring
0017 concatstrings                2
0019 dup
0020 setlocal_WC_0                s@1
0022 leave

Note that the interpolated string does not appear, as it has been compiled to one call to x.to_s (instruction 0013) and one to the concatstrings VM instruction (instruction 0017).

On the other hand, a solution like:

x=1
s="%{foo}" % {foo: x}

Will, on every invocation, push a format string onto the stack (instruction 0003) and invoke String#% (instruction 0007) to re-parse it, essentially triggering the same format-parsing code described in the Kernel::sprintf documentation.

$ ruby --dump=insns <<EXAMPLE
> x=1
> s="%{foo}" % {foo: x}
> EXAMPLE
== disasm: #<ISeq:<main>@-:1 (1,0)-(2,21)> (catch: FALSE)
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] x@0        [ 1] s@1
0000 putobject_INT2FIX_1_                                             (   1)[Li]
0001 setlocal_WC_0                x@0
0003 putstring                    "%{foo}"                            (   2)[Li]
0005 getlocal_WC_0                x@0
0007 opt_send_without_block       <callinfo!mid:%, argc:1, kw:[foo], KWARG>, <callcache>
0010 dup
0011 setlocal_WC_0                s@1
0013 leave

Most use cases won't care about this distinction, but if you came to this question because you do, there you go.


问:
MySQL - I have an issue with blank space
I have a drop down list on a form with values:

```<code>Value One
Value Two
Value Three
</code>```

The values go into a db.

I have another db with columns

```<code>Value One
Value Two
Value Three
</code>```

I have an IF statement that if form Value One to get records in db from Colum Value One.

But getting error message Unknown column 'Value' in 'field list'

I think it has to do with the space? Can I have spaces in the names in MYSQL? If I change it to Value_One, Value_Two, Value_Three can I change the form input Value to be Value%One, Value%Two, Value%Three etc will that work? Ideas?

答:
You can wrap column names, table names, and other identifiers that contain spaces or keywords (like "select") with backticks:

```<code>`Value One`
</code>```

However, from the sound of it, I'm not sure that is your only issue. A use case where you select a column name in a form and submit it is a strange one.

Is it possible that you are trying to get the values from a single column of the database, instead of multiple columns?

Use DESC tablename to find out the column names.

Body:
I have a drop down list on a form with values:

Value One
Value Two
Value Three

The values go into a db.

I have another db with columns

Value One
Value Two
Value Three

I have an IF statement that if form Value One to get records in db from Colum Value One.

But getting error message Unknown column 'Value' in 'field list'

I think it has to do with the space? Can I have spaces in the names in MYSQL? If I change it to Value_One, Value_Two, Value_Three can I change the form input Value to be Value%One, Value%Two, Value%Three etc will that work? Ideas?

Body:
You can wrap column names, table names, and other identifiers that contain spaces or keywords (like "select") with backticks:

`Value One`

However, from the sound of it, I'm not sure that is your only issue. A use case where you select a column name in a form and submit it is a strange one.

Is it possible that you are trying to get the values from a single column of the database, instead of multiple columns?

Use DESC tablename to find out the column names.


问:
Spring Boot with JPA - wrong column type encountered in column
I'm using Spring Boot Starter Data Jpa (2.1.9.RELEASE) and I'm trying to map this table:

CREATE TABLE `foo` (
  `id` int(11) NOT NULL,
  `woo` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

<p>The Entity is mapped as follows:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "foo")
public class Foo {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "woo")
    private Integer woo;

    public Integer getId() {
        return id;
    }

    public Integer getWoo() {
        return woo;
    }

}
</code>```

When I start the application I get the following error:

```<code>Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [woo] in table [foo]; found [tinyint (Types#TINYINT)], but expecting [integer (Types#INTEGER)]
</code>```

My properties are:

```<code>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=validate
</code>```

I tried to do the same mapping using vanilla Jpa and Hibernate (not managed by Spring) and it works fine.

Can anyone point me in the right direction?

Here's a link to the maven project, in case anyone want to try it directly.

答:
You probably need to override the default JDBC type Hibernate using an explicit type declaration:

```<code>@Column(name = "woo", columnDefinition = "TINYINT(4)")
private Integer woo;
</code>```

This should fix.

Body:
I'm using Spring Boot Starter Data Jpa (2.1.9.RELEASE) and I'm trying to map this table:

CREATE TABLE `foo` (
  `id` int(11) NOT NULL,
  `woo` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The Entity is mapped as follows:

@Entity
@Table(name = "foo")
public class Foo {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "woo")
    private Integer woo;

    public Integer getId() {
        return id;
    }

    public Integer getWoo() {
        return woo;
    }

}

When I start the application I get the following error:

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [woo] in table [foo]; found [tinyint (Types#TINYINT)], but expecting [integer (Types#INTEGER)]

My properties are:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=validate

I tried to do the same mapping using vanilla Jpa and Hibernate (not managed by Spring) and it works fine.

Can anyone point me in the right direction?

Here's a link to the maven project, in case anyone want to try it directly.

Body:
You probably need to override the default JDBC type Hibernate using an explicit type declaration:

@Column(name = "woo", columnDefinition = "TINYINT(4)")
private Integer woo;

This should fix.


问:
Scala create immutable nested map
I have a situation here

I have two strins

```<code>val keyMap = "anrodiApp,key1;iosApp,key2;xyz,key3"
val tentMap = "androidApp,tenant1; iosApp,tenant1; xyz,tenant2"
</code>```

So what I want to add is to create a nested immutable nested map like this

```<code>tenant1 -> (andoidiApp -> key1, iosApp -> key2),
tenant2 -> (xyz -> key3)
</code>```

So basically want to group by tenant and create a map of keyMap

Here is what I tried but is done using mutable map which I do want, is there a way to create this using immmutable map

```<code>case class TenantSetting() {
  val requesterKeyMapping = new mutable.HashMap[String, String]()
}

val requesterKeyMapping = keyMap.split(";")
      .map { keyValueList => keyValueList.split(',')
        .filter(_.size==2)
        .map(keyValuePair => (keyValuePair[0],keyValuePair[1]))
        .toMap
      }.flatten.toMap

    val config = new mutable.HashMap[String, TenantSetting]

    tentMap.split(";")
      .map { keyValueList => keyValueList.split(',')
        .filter(_.size==2)
        .map { keyValuePair =>
          val requester = keyValuePair[0]
          val tenant = keyValuePair[1]
          if (!config.contains(tenant)) config.put(tenant, new TenantSetting)
          config.get(tenant).get.requesterKeyMapping.put(requester, requesterKeyMapping.get(requester).get)
        }
      }
</code>```

答:
The logic to break the strings into a map can be the same for both as it's the same syntax.

What you had for the first string was not quite right as the filter you were applying to each string from the split result and not on the array result itself.  Which also showed in that you were using [] on keyValuePair which was of type String and not Array[String] as I think you were expecting.   Also you needed a trim in there to cope with the spaces in the second string.   You might want to also trim the key and value to avoid other whitespace issues.

Additionally in this case the combination of map and filter can be more succinctly done with collect as shown here:
How to convert an Array to a Tuple?
The use of the pattern with 2 elements ensures you filter out anything with length other than 2 as you wanted.
The iterator is to make the combination of map and collect more efficient by only requiring one iteration of the collection returned from the first split (see comments below).
With both strings turned into a map it just needs the right use of groupByto group the first map by the value of the second based on the same key to get what you wanted.  Obviously this only works if the same key is always in the second map.

```<code>def toMap(str: String): Map[String, String] =
  str
    .split(";")
    .iterator
    .map(_.trim.split(','))
    .collect { case Array(key, value) => (key.trim, value.trim) }
    .toMap

val keyMap = toMap("androidApp,key1;iosApp,key2;xyz,key3")
val tentMap = toMap("androidApp,tenant1; iosApp,tenant1; xyz,tenant2")

val finalMap = keyMap.groupBy { case (k, _) => tentMap(k) }
</code>```

Printing out finalMap gives:

```<code>Map(tenant2 -> Map(xyz -> key3), tenant1 -> Map(androidApp -> key1, iosApp -> key2))
</code>```

Which is what you wanted.

Title: Scala create immutable nested map

Body:
I have a situation here

I have two strins

val keyMap = "anrodiApp,key1;iosApp,key2;xyz,key3"
val tentMap = "androidApp,tenant1; iosApp,tenant1; xyz,tenant2"

So what I want to add is to create a nested immutable nested map like this

tenant1 -> (andoidiApp -> key1, iosApp -> key2),
tenant2 -> (xyz -> key3)

So basically want to group by tenant and create a map of keyMap

Here is what I tried but is done using mutable map which I do want, is there a way to create this using immmutable map

case class TenantSetting() {
  val requesterKeyMapping = new mutable.HashMap[String, String]()
}

val requesterKeyMapping = keyMap.split(";")
      .map { keyValueList => keyValueList.split(',')
        .filter(_.size==2)
        .map(keyValuePair => (keyValuePair[0],keyValuePair[1]))
        .toMap
      }.flatten.toMap

    val config = new mutable.HashMap[String, TenantSetting]

    tentMap.split(";")
      .map { keyValueList => keyValueList.split(',')
        .filter(_.size==2)
        .map { keyValuePair =>
          val requester = keyValuePair[0]
          val tenant = keyValuePair[1]
          if (!config.contains(tenant)) config.put(tenant, new TenantSetting)
          config.get(tenant).get.requesterKeyMapping.put(requester, requesterKeyMapping.get(requester).get)
        }
      }

Body:
The logic to break the strings into a map can be the same for both as it's the same syntax.

What you had for the first string was not quite right as the filter you were applying to each string from the split result and not on the array result itself.  Which also showed in that you were using [] on keyValuePair which was of type String and not Array[String] as I think you were expecting.   Also you needed a trim in there to cope with the spaces in the second string.   You might want to also trim the key and value to avoid other whitespace issues.

Additionally in this case the combination of map and filter can be more succinctly done with collect as shown here:
How to convert an Array to a Tuple?
The use of the pattern with 2 elements ensures you filter out anything with length other than 2 as you wanted.
The iterator is to make the combination of map and collect more efficient by only requiring one iteration of the collection returned from the first split (see comments below).
With both strings turned into a map it just needs the right use of groupByto group the first map by the value of the second based on the same key to get what you wanted.  Obviously this only works if the same key is always in the second map.

def toMap(str: String): Map[String, String] =
  str
    .split(";")
    .iterator
    .map(_.trim.split(','))
    .collect { case Array(key, value) => (key.trim, value.trim) }
    .toMap

val keyMap = toMap("androidApp,key1;iosApp,key2;xyz,key3")
val tentMap = toMap("androidApp,tenant1; iosApp,tenant1; xyz,tenant2")

val finalMap = keyMap.groupBy { case (k, _) => tentMap(k) }

Printing out finalMap gives:

Map(tenant2 -> Map(xyz -> key3), tenant1 -> Map(androidApp -> key1, iosApp -> key2))

Which is what you wanted.


问:
Tensorflow import issue Python 3.6
I am trying to learn how to create a Machine Learning Algorithm by following a tutorial on YouTube and I am currently stuck on the last part of the last video. I got tensorflow and keras to install without issue, but every time I call import tensorflow inside the PyCharm editor it gives me these two back traces

```<code>Traceback (most recent call last):<br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
<br/><br/>
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
<br/><br/>
During handling of the above exception, another exception occurred:
<br/><br/>
Traceback (most recent call last):<br/>
  File "C:/Users/Le Quient LewisII/PycharmProjects/tensorEnv/test.py", line 1, in <module>
    import tensorflow
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow\__init__.py", line 98, in <module>
    from tensorflow_core import *
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module>
    from tensorflow.python.tools import module_util as _module_util
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)<br/><br/>
ImportError: Traceback (most recent call last):<br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
<br/><br/>
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
<br/><br/>
ImportError: DLL load failed: A dynamic link library (DLL)
initialization routine failed.
</code>```

And I do not know what they mean. I tried uninstalling and reinstalling tensorflow, but it still persists. If there is anyone who can assist me with this problem, it would be greatly appreciated?

答: Okay, so I figured out what my issue was. It was a RAM issue and so I switched to another laptop and it works perfectly fine now. Sorry, for the long wait</p>

Title: Tensorflow import issue Python 3.6

Body:
I am trying to learn how to create a Machine Learning Algorithm by following a tutorial on YouTube and I am currently stuck on the last part of the last video. I got tensorflow and keras to install without issue, but every time I call import tensorflow inside the PyCharm editor it gives me these two back traces

Traceback (most recent call last):

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 343, in load_dynamic
    return _load(spec)

ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:/Users/Le Quient LewisII/PycharmProjects/tensorEnv/test.py", line 1, in <module>
    import tensorflow
  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow\__init__.py", line 98, in <module>
    from tensorflow_core import *

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module>
    from tensorflow.python.tools import module_util as _module_util

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)

ImportError: Traceback (most recent call last):

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)

  File "C:\Users\Le Quient LewisII\Anaconda3\envs\tensor\lib\imp.py", line 343, in load_dynamic
    return _load(spec)

ImportError: DLL load failed: A dynamic link library (DLL)
initialization routine failed.

And I do not know what they mean. I tried uninstalling and reinstalling tensorflow, but it still persists. If there is anyone who can assist me with this problem, it would be greatly appreciated?


问:
Practical differences between explicitly subscribing to an Observable vs calling subscribe() with parameter
I have a service that returns an Observable:

```<code>contactsSerice (): Observable<Contact[]> {...}
</code>```

For using this data on my template and keep the template "alive" based on what's in the Observable I've found two ways.

I declared a Subject within the context of my Component:

```<code>export class ExampleComponent implements OnInit {

    contacts$: Subject<Contact[]> = new Subject<Contact[]>();
    constructor(){}

}
</code>```

And then:

Explicitly subscribing to the Observable (and emitting the contacts) like this:

```<code>ngOnInit() {

   this.contactsSerice().subscribe((contacts: Contact[]) => {
           this.contacts$.next(contacts);
   });
}
</code>```

Calling directly the .subscribe() using my Subject as a parameter:

```<code>ngOnInit() {
  this.contactsSerice().subscribe(this.contacts$);
}
</code>```

After this, I can use the | async pipe in the template like:

```<code><section *ngIf="contacts$ | async as contacts">
...
</section>
</code>```

I was wondering if there's any practical difference between calling subscribe() passing the Subject vs properly subscribing to the Observable and trigger the Subject's next() method.

答:
There is an actual difference:

When we are subscribing via a Subject then error and complete notifications are passed to it. So if our source observable is completing, then the subject is completing as well. This might be an unwanted behaviour, because a completed Subject does ignore all further notifications.

 /*
 Variant 1:
   This works only once:
     - The complete notification from the HTTP call is forwarded to the subscribing subject
     - A completed subject ignores further values
 */
 this.inventoryService.loadBeers(page).subscribe(this.beers$);

 // could be thought of the same as:
 this.inventoryService.loadBeers()
   .subscribe(
     (response) => this.beers$.next(response),
     (error) => this.beers$.error(error),
     () => this.beers$.complete()
 );

 /*
  Variant 2: Here we don't pass the completed event to the beers$
 */
 this.inventoryService.loadBeers()
   .subscribe(
     (response) => this.beers$.next(response),
     (error) => console.log('Errors are not passed to beers$ subject'),
     () => console.log('Complete notification is not passed to beers$ subject')
 );
```

You can also take a look at the stackblitz example where I tried to show this behaviour.

Body:
I have a service that returns an Observable:

contactsSerice (): Observable<Contact[]> {...}

For using this data on my template and keep the template "alive" based on what's in the Observable I've found two ways.

I declared a Subject within the context of my Component:

export class ExampleComponent implements OnInit {

    contacts$: Subject<Contact[]> = new Subject<Contact[]>();
    constructor(){}

}

And then:

Explicitly subscribing to the Observable (and emitting the contacts) like this:

ngOnInit() {

   this.contactsSerice().subscribe((contacts: Contact[]) => {
           this.contacts$.next(contacts);
   });
}

Calling directly the .subscribe() using my Subject as a parameter:

ngOnInit() {
  this.contactsSerice().subscribe(this.contacts$);
}

After this, I can use the | async pipe in the template like:

...

I was wondering if there's any practical difference between calling subscribe() passing the Subject vs properly subscribing to the Observable and trigger the Subject's next() method.

Body:
There is an actual difference:

When we are subscribing via a Subject then error and complete notifications are passed to it. So if our source observable is completing, then the subject is completing as well. This might be an unwanted behaviour, because a completed Subject does ignore all further notifications.

 /*
 Variant 1:
   This works only once:
     - The complete notification from the HTTP call is forwarded to the subscribing subject
     - A completed subject ignores further values
 */
 this.inventoryService.loadBeers(page).subscribe(this.beers$);

 // could be thought of the same as:
 this.inventoryService.loadBeers()
   .subscribe(
     (response) => this.beers$.next(response),
     (error) => this.beers$.error(error),
     () => this.beers$.complete()
 );

 /*
  Variant 2: Here we don't pass the completed event to the beers$
 */
 this.inventoryService.loadBeers()
   .subscribe(
     (response) => this.beers$.next(response),
     (error) => console.log('Errors are not passed to beers$ subject'),
     () => console.log('Complete notification is not passed to beers$ subject')
 );

You can also take a look at the stackblitz example where I tried to show this behaviour.


问:
MARS Mips Adding more than 2 registers/printing solution
I did a few calculations (not even sure if they're remotely close to accurate as the instructions for the assignment are non existent (thanks worthless professors)) but basically I'm trying to take the value of $t2, $t3, $t4, and $t5.. add them together, then store them in $t6 and print that to the console.

Heres what I have so far

```<code>    li $v0,10
    li $t1, 10
    add $t2, $t1, $t1
    sll $t3, $t1, 2
    and $t4, $t1, 0x0000FFFF
    or $t5, $t1, 0x0000FFFF
</code>```

答:
This should do the job.

```<code>    .data ## Data declaration section
    .text ## Assembly language instructions go in text segment
main: ## Start of code section
    add $t1, $t2, $t3 # t1 = t2 + t3
    add $t2, $t4, $t5 # t2 = t4 + t5
    add $t6, $t2, $t1 # t6 = t1 + t2
    move $a0, $t6 # a0 = t6
    li $v0, 1 # system call code to print integer from a0
    syscall # call operating system to perform operation
    li $v0, 10 # terminate program
    syscall
</code>```

Found the example Hello World! program here: https://courses.cs.vt.edu/cs2506/Fall2014/Notes/L04.MIPSAssemblyOverview.pdf

Which I extended according to your requirements.

This code will output 0 if you run it on MARS simulator, since t2, t3, t4, t5 are 0 basically.

Body:
I did a few calculations (not even sure if they're remotely close to accurate as the instructions for the assignment are non existent (thanks worthless professors)) but basically I'm trying to take the value of $t2, $t3, $t4, and $t5.. add them together, then store them in $t6 and print that to the console.

Heres what I have so far

    li $v0,10
    li $t1, 10
    add $t2, $t1, $t1
    sll $t3, $t1, 2
    and $t4, $t1, 0x0000FFFF
    or $t5, $t1, 0x0000FFFF

Body:
This should do the job.

    .data ## Data declaration section
    .text ## Assembly language instructions go in text segment
main: ## Start of code section
    add $t1, $t2, $t3 # t1 = t2 + t3
    add $t2, $t4, $t5 # t2 = t4 + t5
    add $t6, $t2, $t1 # t6 = t1 + t2
    move $a0, $t6 # a0 = t6
    li $v0, 1 # system call code to print integer from a0
    syscall # call operating system to perform operation
    li $v0, 10 # terminate program
    syscall

Found the example Hello World! program here: https://courses.cs.vt.edu/cs2506/Fall2014/Notes/L04.MIPSAssemblyOverview.pdf

Which I extended according to your requirements.

This code will output 0 if you run it on MARS simulator, since t2, t3, t4, t5 are 0 basically.


问:
Implementation of two for loops in React Js to create a 3X3 square marix box for tic-tac-toe
I'm following the React Js tutorial from the official site which helps us build a tic-tac-toe game. The square boxes are created by hardcoding all the squares as follows:

```<code>render(){
  return (
    <div>
      <div className = "board-row">
        {this.renderSquare(0)}
        {this.renderSquare(1)}
        {this.renderSquare(2)}
      </div>
      <div className = "board-row">
        {this.renderSquare(3)}
        {this.renderSquare(4)}
        {this.renderSquare(5)}
      </div>
      <div className = "board-row">
        {this.renderSquare(6)}
        {this.renderSquare(7)}
        {this.renderSquare(8)}
      </div>
    </div>
  );
}
</code>```

I managed to shorten the code by using a for loop as shown below:

```<code>render(){
  let sqrRen = [];
  for(let i = 0; i < 9; i=i+3){
    sqrRen.push(<div className = "board-row">
      {this.renderSquare(0+i)}
      {this.renderSquare(1+i)}
      {this.renderSquare(2+i)}
    </div>);
  }
  return (
    <div>
        {sqrRen}
    </div>
  );
}
</code>```

But I also want to generate the squares in each row using another for loop as follows:

```<code>render(){
  let sqrRen = [];
  for(let i = 0; i < 9; i=i+3){
    sqrRen.push(<div className = "board-row">
      {
        for(let j=0;j<3;j++){
        this.renderSquare(j+i)
        }
      }
    </div>);
  }

  return (
    <div>
      {sqrRen}
    </div>
  );
}
</code>```

but this is not working. I get the following error:

Any suggestions on how to go about using two for loops?

答:
You have to create the element structure first, then pass it to the container element.

```<code>class Board extends React.Component {
renderSquare(i) {
    return (
        <Square
        //give each square its unique key
            key={i}
            value={this.props.squares[i]}
            onClick={() => this.props.onClick(i)}
        />
    );
}

fillBoard=()=>{
    //make an empty array for storing the rows
    let rows =[];
    //a function scoped counter for keeping track of current square
    let counter = 0;
    for(let x = 0; x<3; x++){
        //create an array to store each child of board-row (square)
        let rowSquares = [];
        for(let y = 0;y<3;y++){
            //fill the second array with the children (squares)
            rowSquares.push(this.renderSquare(counter));
            //increase function scoped variable to track current square
            counter++;
        }
    //push each row object into the first array with the children array included
     rows.push(<div className="board-row" key={x}>{rowSquares}</div>)
    }
    //return the rows array
    return rows;
}

render() {
    //render the parent container div with its child the rows array
   return(<div>{this.fillBoard()}</div>)
}}
</code>```

Double for loops can be confusing on their own, adding react to the equation doesn't help.
In plain English what you are doing is saying:

Lets make an array to store our row objects

Make a for loop to iterate how ever many rows we need.

Now that we are inside of our first loop, lets make an empty array specific to this iteration of our first row object, where we will store its children.

Create a second for loop to iterate over each child we want to add to this row.

Now that the second loop has added each square to the row parent and is done, we move back into the FIRST loop to finish up by simply adding this completed row object and its children (the squares) to the function scoped array for storing the rows we made before the loops.

When we want to render, we just call that function and put the returned object (our nifty list of rows and squares tree array) inside of our container div.

Body:
I'm following the React Js tutorial from the official site which helps us build a tic-tac-toe game. The square boxes are created by hardcoding all the squares as follows:

render(){
  return (

        {this.renderSquare(0)}
        {this.renderSquare(1)}
        {this.renderSquare(2)}

        {this.renderSquare(3)}
        {this.renderSquare(4)}
        {this.renderSquare(5)}

        {this.renderSquare(6)}
        {this.renderSquare(7)}
        {this.renderSquare(8)}

  );
}

I managed to shorten the code by using a for loop as shown below:

render(){
  let sqrRen = [];
  for(let i = 0; i < 9; i=i+3){
    sqrRen.push(

      {this.renderSquare(0+i)}
      {this.renderSquare(1+i)}
      {this.renderSquare(2+i)}

);
  }
  return (

        {sqrRen}

  );
}

But I also want to generate the squares in each row using another for loop as follows:

render(){
  let sqrRen = [];
  for(let i = 0; i < 9; i=i+3){
    sqrRen.push(

      {
        for(let j=0;j<3;j++){
        this.renderSquare(j+i)
        }
      }

);
  }

  return (

      {sqrRen}

  );
}

but this is not working. I get the following error:

Any suggestions on how to go about using two for loops?

Body:
You have to create the element structure first, then pass it to the container element.

class Board extends React.Component {
renderSquare(i) {
    return (
        <Square
        //give each square its unique key
            key={i}
            value={this.props.squares[i]}
            onClick={() => this.props.onClick(i)}
        />
    );
}

fillBoard=()=>{
    //make an empty array for storing the rows
    let rows =[];
    //a function scoped counter for keeping track of current square
    let counter = 0;
    for(let x = 0; x<3; x++){
        //create an array to store each child of board-row (square)
        let rowSquares = [];
        for(let y = 0;y<3;y++){
            //fill the second array with the children (squares)
            rowSquares.push(this.renderSquare(counter));
            //increase function scoped variable to track current square
            counter++;
        }
    //push each row object into the first array with the children array included
     rows.push(<div className="board-row" key={x}>{rowSquares}</div>)
    }
    //return the rows array
    return rows;
}

render() {
    //render the parent container div with its child the rows array
   return(<div>{this.fillBoard()}</div>)
}}

Double for loops can be confusing on their own, adding react to the equation doesn't help.
In plain English what you are doing is saying:

Lets make an array to store our row objects

Make a for loop to iterate how ever many rows we need.

Now that we are inside of our first loop, lets make an empty array specific to this iteration of our first row object, where we will store its children.

Create a second for loop to iterate over each child we want to add to this row.

Now that the second loop has added each square to the row parent and is done, we move back into the FIRST loop to finish up by simply adding this completed row object and its children (the squares) to the function scoped array for storing the rows we made before the loops.

When we want to render, we just call that function and put the returned object (our nifty list of rows and squares tree array) inside of our container div.


问:
Can someone explain me this while loop what means?
```<code>while (a = b)
   ;
</code>```

I know that it will probably not be anything so complex but I don't understand what it will become

答:
Assuming that a and b are variables...

What this says is "Assign the value of b to a. If this value is non zero, do the inside of the loop (which is "do nothing"). Continue assigning until a (post assignment) is zero."

Theoretically, b could be changed throughout the program via an interrupt or other source. It could be mapped to an internal register, for example. Note that this is also changing a, which could set off a chain of events that makes b zero, ending the loop.

If b and a are not changing/are not volatile, this could serve (in a jankey way) as "clear a, assert that b is zero." If b is non-zero, the program will hang.

Most likely though, it's meant to be while (a == b);, which can be treated as "assert that a is not equal to b, and hang otherwise."

Body:
while (a = b)
   ;

I know that it will probably not be anything so complex but I don't understand what it will become


问:
Vuetify: Dependent v-select based on selection
I made a codepent - example:
https://codepen.io/rasenkantenstein/pen/qBdZepM

The user should choose a country and eventually only select the cities belonging to a country. However, there's an array behind the data of the people. How can I tell Vue(tify) to alter only those items from the currently edited row?

```<code>    changeCity(index, country) {
     //How can I filter the cities here for each person?
     let result = this.cities.filter(city => {
       return city.country == country
     })
     console.log(result)
     //this works on all fields... ? --> this.cities = result
   }
</code>```

答:
You should filter the cities based on the person country, inside your v-select, like this:</p>

```<code>:items="cities.filter(c => c.country === person.country)"
</code>```

Body:
I made a codepent - example:
https://codepen.io/rasenkantenstein/pen/qBdZepM

The user should choose a country and eventually only select the cities belonging to a country. However, there's an array behind the data of the people. How can I tell Vue(tify) to alter only those items from the currently edited row?

    changeCity(index, country) {
     //How can I filter the cities here for each person?
     let result = this.cities.filter(city => {
       return city.country == country
     })
     console.log(result)
     //this works on all fields... ? --> this.cities = result
   }

Body:
You should filter the cities based on the person country, inside your v-select, like this:

:items="cities.filter(c => c.country === person.country)"


问:
English grammar for parsing in NLTK
Is there a ready-to-use English grammar that I can just load it and use in NLTK? I've searched around examples of parsing with NLTK, but it seems like that I have to manually specify grammar before parsing a sentence.

Thanks a lot!

答:
I'm found out that nltk working good with parser grammar developed by Stanford.

Syntax Parsing with Stanford CoreNLP and NLTK

It is very easy to start to use Stanford CoreNLP and NLTK. All you need is small preparation, after that you can parse sentences with following code:

```<code>from nltk.parse.corenlp import CoreNLPParser
parser = CoreNLPParser()
parse = next(parser.raw_parse("I put the book in the box on the table."))
</code>```

Preparation:

Download Java Stanford model

Run CoreNLPServer

You can use following code to run CoreNLPServer:

```<code>import os
from nltk.parse.corenlp import CoreNLPServer
# The server needs to know the location of the following files:
#   - stanford-corenlp-X.X.X.jar
#   - stanford-corenlp-X.X.X-models.jar
STANFORD = os.path.join("models", "stanford-corenlp-full-2018-02-27")
# Create the server
server = CoreNLPServer(
   os.path.join(STANFORD, "stanford-corenlp-3.9.1.jar"),
   os.path.join(STANFORD, "stanford-corenlp-3.9.1-models.jar"),
)
# Start the server in the background
server.start()
</code>```

Do not forget stop server with executing server.stop()

Title: English grammar for parsing in NLTK

Body:
I'm found out that nltk working good with parser grammar developed by Stanford.

Syntax Parsing with Stanford CoreNLP and NLTK

It is very easy to start to use Stanford CoreNLP and NLTK. All you need is small preparation, after that you can parse sentences with following code:

from nltk.parse.corenlp import CoreNLPParser
parser = CoreNLPParser()
parse = next(parser.raw_parse("I put the book in the box on the table."))

Preparation:

Download Java Stanford model

Run CoreNLPServer

You can use following code to run CoreNLPServer:

import os
from nltk.parse.corenlp import CoreNLPServer
# The server needs to know the location of the following files:
#   - stanford-corenlp-X.X.X.jar
#   - stanford-corenlp-X.X.X-models.jar
STANFORD = os.path.join("models", "stanford-corenlp-full-2018-02-27")
# Create the server
server = CoreNLPServer(
   os.path.join(STANFORD, "stanford-corenlp-3.9.1.jar"),
   os.path.join(STANFORD, "stanford-corenlp-3.9.1-models.jar"),
)
# Start the server in the background
server.start()

Do not forget stop server with executing server.stop()


问:
determining whether two convex hulls overlap
I'm trying to find an efficient algorithm for determining whether two convex hulls intersect or not.  The hulls consist of data points in N-dimensional space, where N is 3 up to 10 or so.  One elegant algorithm was suggested here using linprog from scipy, but you have to loop over all points in one hull, and it turns out the algorithm is very slow for low dimensions (I tried it and so did one of the respondents).  It seems to me the algorithm could be generalized to answer the question I am posting here, and I found what I think is a solution here.  The authors say that the general linear programming problem takes the form Ax + tp >= 1, where the A matrix contains the points of both hulls, t is some constant >= 0, and p = [1,1,1,1...1] (it's equivalent to finding a solution to Ax > 0 for some x).  As I am new to linprog() it isn't clear to me whether it can handle problems of this form.  If A_ub is defined as on page 1 of the paper, then what is b_ub?

答:
There is a nice explanation of how to do this problem, with an algorithm in R, on this website.  My original post referred to the scipy.optimize.linprog library, but this proved to be insufficiently robust.  I found that the SCS algorithm in the cvxpy library worked very nicely, and based on this I came up with the following python code:

```<code>import numpy as np
import cvxpy as cvxpy

# Determine feasibility of Ax <= b
# cloud1 and cloud2 should be numpy.ndarrays
def clouds_overlap(cloud1, cloud2):
    # build the A matrix
    cloud12 = np.vstack((-cloud1, cloud2))
    vec_ones = np.r_[np.ones((len(cloud1),1)), -np.ones((len(cloud2),1))]
    A = np.r_['1', cloud12, vec_ones]

    # make b vector
    ntot = len(cloud1) + len(cloud2)
    b = -np.ones(ntot)

    # define the x variable and the equation to be solved
    x = cvxpy.Variable(A.shape[1])
    constraints = [A*x <= b]

    # since we're only determining feasibility there is no minimization
    # so just set the objective function to a constant
    obj = cvxpy.Minimize(0)

    # SCS was the most accurate/robust of the non-commercial solvers
    # for my application
    problem = cvxpy.Problem(obj, constraints)
    problem.solve(solver=cvxpy.SCS)

    # Any 'inaccurate' status indicates ambiguity, so you can
    # return True or False as you please
    if problem.status == 'infeasible' or problem.status.endswith('inaccurate'):
        return True
    else:
        return False

cube = np.array([[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]])
inside = np.array([[0.49,0.0,0.0]])
outside = np.array([[1.01,0,0]])

print("Clouds overlap?", clouds_overlap(cube, inside))
print("Clouds overlap?", clouds_overlap(cube, outside))

# Clouds overlap? True
# Clouds overlap? False
</code>```

The area of numerical instability is when the two clouds just touch, or are arbitrarily close to touching such that it isn't possible to definitively say whether they overlap or not.  That is one of the cases where you will see this algorithm report an 'inaccurate' status.  In my code I chose to consider such cases overlapping, but since it is ambiguous you can decide for yourself what to do.

Body:
There is a nice explanation of how to do this problem, with an algorithm in R, on this website.  My original post referred to the scipy.optimize.linprog library, but this proved to be insufficiently robust.  I found that the SCS algorithm in the cvxpy library worked very nicely, and based on this I came up with the following python code:

import numpy as np
import cvxpy as cvxpy

# Determine feasibility of Ax <= b
# cloud1 and cloud2 should be numpy.ndarrays
def clouds_overlap(cloud1, cloud2):
    # build the A matrix
    cloud12 = np.vstack((-cloud1, cloud2))
    vec_ones = np.r_[np.ones((len(cloud1),1)), -np.ones((len(cloud2),1))]
    A = np.r_['1', cloud12, vec_ones]

    # make b vector
    ntot = len(cloud1) + len(cloud2)
    b = -np.ones(ntot)

    # define the x variable and the equation to be solved
    x = cvxpy.Variable(A.shape[1])
    constraints = [A*x <= b]

    # since we're only determining feasibility there is no minimization
    # so just set the objective function to a constant
    obj = cvxpy.Minimize(0)

    # SCS was the most accurate/robust of the non-commercial solvers
    # for my application
    problem = cvxpy.Problem(obj, constraints)
    problem.solve(solver=cvxpy.SCS)

    # Any 'inaccurate' status indicates ambiguity, so you can
    # return True or False as you please
    if problem.status == 'infeasible' or problem.status.endswith('inaccurate'):
        return True
    else:
        return False

cube = np.array([[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]])
inside = np.array([[0.49,0.0,0.0]])
outside = np.array([[1.01,0,0]])

print("Clouds overlap?", clouds_overlap(cube, inside))
print("Clouds overlap?", clouds_overlap(cube, outside))

# Clouds overlap? True
# Clouds overlap? False

The area of numerical instability is when the two clouds just touch, or are arbitrarily close to touching such that it isn't possible to definitively say whether they overlap or not.  That is one of the cases where you will see this algorithm report an 'inaccurate' status.  In my code I chose to consider such cases overlapping, but since it is ambiguous you can decide for yourself what to do.


问:
Get Current User in a Blazor component
I'm starting a new site with Blazor and Windows Authentication and need to identify the current user viewing the page/component.

For a Razor Page, the current user name can be accessed with Context.User.Identity.Name, but that doesn't seem to work in a Blazor component.  I've tried injecting HttpContext into the component but the Context is null at runtime.

As a bonus, I will eventually want to incorporate this into Startup.cs so I only need to get the username once and can leverage a corporate user class (with EF Core) for my applications.  Answers tailored to that use case would also be appreciated.

答:
UPDATE - This answer does not work.  Rather than deleting it, I've let it here as information.  Please consider the other answers for the question instead.

In ConfigureServices, in Startup.cs, add
services.AddHttpContextAccessor();

In your component class [Note: I use code-behind with null types enabled]

```<code>        [Inject]
        private IHttpContextAccessor HttpContextAccessor { get; set; } = default!;

        private string username = default!;
</code>```

In your component code (code behind), in protected override void OnInitialized()

```<code>        username = HttpContextAccessor.HttpContext.User.Identity.Name;
</code>```

username can now be used throughout the component just like any other variable.

However, see my other answer in this question to add get the current user name from a service usable in any class.

Title: Get Current User in a Blazor component

Body:
UPDATE - This answer does not work.  Rather than deleting it, I've let it here as information.  Please consider the other answers for the question instead.

In ConfigureServices, in Startup.cs, add
services.AddHttpContextAccessor();

In your component class [Note: I use code-behind with null types enabled]

        [Inject]
        private IHttpContextAccessor HttpContextAccessor { get; set; } = default!;

        private string username = default!;

In your component code (code behind), in protected override void OnInitialized()

        username = HttpContextAccessor.HttpContext.User.Identity.Name;

username can now be used throughout the component just like any other variable.

However, see my other answer in this question to add get the current user name from a service usable in any class.


问:
Column alias in `ORDER BY` expression?
In Oracle 12.1.0.2 and Oracle 19c, this query:

```<code>with test_data (c1, c2) AS (
SELECT 'A', 1 FROM DUAL UNION ALL
SELECT 'B', 2 FROM DUAL UNION ALL
SELECT 'C', 3 FROM DUAL )
SELECT c1, c2*-1 c2
FROM test_data
order by c2*-1;
</code>```

Returns:

```<code>+----+----+
| C1 | C2 |
+----+----+
| A  | -1 |
| B  | -2 |
| C  | -3 |
+----+----+
</code>```

In other words, the c2 in ORDER BY c2*-1 referring to the c2 column alias in the SELECT list and NOT the c2 column in the database table.

My reading of the Oracle SQL Reference Guide makes me think that the query result above is incorrect and that it is not appropriate for Oracle to think that an identifier in an ORDER BY expression refers to a column alias.

Has Oracle always behaved like this and I just never noticed?  Is there something in Oracle's documentation that indicates the results above are correct and expected?

答:
The documentation seems quite clear to me:

expr

expr orders rows based on their value for expr. The expression is based on columns in the select list or columns in the tables, views, or materialized views in the FROM clause.

It actually references the "columns" in the select list first (by which it means aliases).

If you want the table column, use an alias:

```<code>order by test_data.c2 * -1
</code>```

Title: Column alias in `ORDER BY` expression?

Body:
In Oracle 12.1.0.2 and Oracle 19c, this query:

with test_data (c1, c2) AS (
SELECT 'A', 1 FROM DUAL UNION ALL
SELECT 'B', 2 FROM DUAL UNION ALL
SELECT 'C', 3 FROM DUAL )
SELECT c1, c2*-1 c2
FROM test_data
order by c2*-1;

Returns:

+----+----+
| C1 | C2 |
+----+----+
| A  | -1 |
| B  | -2 |
| C  | -3 |
+----+----+

In other words, the c2 in ORDER BY c2*-1 referring to the c2 column alias in the SELECT list and NOT the c2 column in the database table.

My reading of the Oracle SQL Reference Guide makes me think that the query result above is incorrect and that it is not appropriate for Oracle to think that an identifier in an ORDER BY expression refers to a column alias.

Has Oracle always behaved like this and I just never noticed?  Is there something in Oracle's documentation that indicates the results above are correct and expected?

Body:
The documentation seems quite clear to me:

expr

expr orders rows based on their value for expr. The expression is based on columns in the select list or columns in the tables, views, or materialized views in the FROM clause.

It actually references the "columns" in the select list first (by which it means aliases).

If you want the table column, use an alias:

order by test_data.c2 * -1


问:
Fill between 4 points: Matplotlib won't let me add more points
I'm trying to make a bounding box. I have all the coordinates. Now, I need to fill between this space. No matter, what combination I try, it won't let me set a limit on y.

What I have:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(np.random.randint(0, 255, (1200, 1200, 3)))

plt.fill_between([1080, 1120], [800, 800], color='blue', alpha=.5)

plt.show()
</code>```

What I need:

The y axis needs to stop around 200.

答:
From the matplotlib documentation, the signature for this function is    matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs), where x is an array and y1/y2 is an array or scalar. You give an array for x and y1, but never y2.

Using plt.fill_between([1080, 1120], 200, 800, color='blue', alpha=.5) should give the result you are looking for.

Body:
I'm trying to make a bounding box. I have all the coordinates. Now, I need to fill between this space. No matter, what combination I try, it won't let me set a limit on y.

What I have:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(np.random.randint(0, 255, (1200, 1200, 3)))

plt.fill_between([1080, 1120], [800, 800], color='blue', alpha=.5)

plt.show()

What I need:

The y axis needs to stop around 200.


问:
How to use one table rows (in like operator) as the parameter for another table in a function?
How to use one table rows (in like operator) as the parameter for another table in a function? </p>

答:
I think this is what you mean.

DECLARE @text varchar(50) = (SELECT Value FROM TABLE WHERE Value like '%descriptor%')


问:
PHP proc_open opens multiple times
I have a utility function used for executing a program through CLI (cmd, bash etc). It returns an array of 3 items: STDOUT, STDERR and EXIT CODE.

So far, it's been working nicely without issues. In fact, the problem I have with it doesn't really hinder it's functionality, but I'm concerned about performance.

The problem is that in certain cases, PHP runs the same command multiple times (3 times in my case), even if it was supposed to only do this once.

```<code>/**
 * Executes a program and waits for it to finish, taking pipes into account.
 * @param string $cmd Command line to execute, including any arguments.
 * @param string $input Data for standard input.
 * @param boolean $log Whether to log execution failures or not (defaults to true).
 * @return array Array of "stdout", "stderr" and "return".
 */
public static function execute($cmd,$stdin=null,$log=true){
    //static $once=true; if(!$once)die; $once=false;
    $proc=proc_open($cmd, array(
        0=>array('pipe','r'),
        1=>array('pipe','w'),
        2=>array('pipe','w')   ), $pipes);
    fwrite($pipes[0],$stdin);                fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);  fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);  fclose($pipes[2]);
    $return=proc_close($proc);
    if($return!=0 && $log)
        xlog('Error: Program execution returned failure.',$stdout,$stderr,$return);
    return array( 'stdout'=>$stdout, 'stderr'=>$stderr, 'return'=>$return );
}
</code>```

Note the commented line (line 9). That was for testing. I enabled it to ensure the target program only runs once (I was thinking my code may be calling the same function somehow).
But even with that line enabled, the program still ran multiple times.

As it is, I have 2 places in my code where I'm executing the same program (on different occasions). The command line is the same for both of them.

However, on one occasion, the program runs once, while in the occasion, PHP runs the program 3 times.

I've been monitoring and seeing this behavior under Process Explorer. I'm using Windows 7 x64. The program is 32 bit, as is PHP.

Edit: The program in question is custom developed, and it doesn't open new processes.

答:
I know this may not be the best option, but this is what I did. Though this was on Linux, but I'm sure there is way to port this to Windows.

What I did, was run pgrep and check if there already existed a command like this and if it did simply exit.
As you said you are running same command (with exact parameters), so just check if there already is a command running and act respectively.

I used this command:

```<code>$pid = shell_exec('pgrep -cfx "/* My command */"');
if ($pid > 1) return -1;
</code>```

Title: PHP proc_open opens multiple times

Body:
I have a utility function used for executing a program through CLI (cmd, bash etc). It returns an array of 3 items: STDOUT, STDERR and EXIT CODE.

So far, it's been working nicely without issues. In fact, the problem I have with it doesn't really hinder it's functionality, but I'm concerned about performance.

The problem is that in certain cases, PHP runs the same command multiple times (3 times in my case), even if it was supposed to only do this once.

/**
 * Executes a program and waits for it to finish, taking pipes into account.
 * @param string $cmd Command line to execute, including any arguments.
 * @param string $input Data for standard input.
 * @param boolean $log Whether to log execution failures or not (defaults to true).
 * @return array Array of "stdout", "stderr" and "return".
 */
public static function execute($cmd,$stdin=null,$log=true){
    //static $once=true; if(!$once)die; $once=false;
    $proc=proc_open($cmd, array(
        0=>array('pipe','r'),
        1=>array('pipe','w'),
        2=>array('pipe','w')   ), $pipes);
    fwrite($pipes[0],$stdin);                fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);  fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);  fclose($pipes[2]);
    $return=proc_close($proc);
    if($return!=0 && $log)
        xlog('Error: Program execution returned failure.',$stdout,$stderr,$return);
    return array( 'stdout'=>$stdout, 'stderr'=>$stderr, 'return'=>$return );
}

Note the commented line (line 9). That was for testing. I enabled it to ensure the target program only runs once (I was thinking my code may be calling the same function somehow).
But even with that line enabled, the program still ran multiple times.

As it is, I have 2 places in my code where I'm executing the same program (on different occasions). The command line is the same for both of them.

However, on one occasion, the program runs once, while in the occasion, PHP runs the program 3 times.

I've been monitoring and seeing this behavior under Process Explorer. I'm using Windows 7 x64. The program is 32 bit, as is PHP.

Edit: The program in question is custom developed, and it doesn't open new processes.

Body:
I know this may not be the best option, but this is what I did. Though this was on Linux, but I'm sure there is way to port this to Windows.

What I did, was run pgrep and check if there already existed a command like this and if it did simply exit.
As you said you are running same command (with exact parameters), so just check if there already is a command running and act respectively.

I used this command:

$pid = shell_exec('pgrep -cfx "/* My command */"');
if ($pid > 1) return -1;


问:
Permission to specific field in Django admin panel
I have a model in Django that I want to add instances to it from the admin panel.

I have few users that will have access to the admin panel to create new posts to the model and I have 2 questions:

It is possible to detect witch user is in the panel to auto-detect the field "Author"? (See the red rectangle in the picture)

Can I disable the option to a specific user to mark the "Published" field as true? (See the green rectangle in the picture)

答:
For pre-populating fields you can override get_form method:

```<code>def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    form.base_fields['author'].initial = request.user
    return form
</code>```

For disabling fields you can override...get_readonly_fields as well:

```<code>class YourModelAdmin(admin.ModelAdmin):

    readonly_fields = ('whatever', ) # whatever fields you have by default
    limited_fiels = ('published', )

    def get_readonly_fields(self, request, obj=None):
        if request.user.groups.filter(name='YourPermissionGroupName').exists():
            return self.limited_fiels
        return super().get_fieldsets(request, obj=obj)
</code>```

You may need to override get_fields as well to remove published from changable fields list as well.

Body:
For pre-populating fields you can override get_form method:

def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    form.base_fields['author'].initial = request.user
    return form

For disabling fields you can override...get_readonly_fields as well:

class YourModelAdmin(admin.ModelAdmin):

    readonly_fields = ('whatever', ) # whatever fields you have by default
    limited_fiels = ('published', )

    def get_readonly_fields(self, request, obj=None):
        if request.user.groups.filter(name='YourPermissionGroupName').exists():
            return self.limited_fiels
        return super().get_fieldsets(request, obj=obj)

You may need to override get_fields as well to remove published from changable fields list as well.