问:
Calling another objectStream.Write text macro within my macro isn't workiing
So I'm creating a macro to output an UTF-8 encoded XML since the source text will sometimes involve Japanese or Chinese characters. I'm trying to break each section of the XML into different chunks so it's easier for me to edit but my call line isn't working. Since I'm not trained in programming and my knowledge is based on looking up VBA macro codes and tweaking them until I get the desired result, I'm stumped as to how to get my objStream macro to not error when calling another objStream line.

Thanks!

Here it is:

```<code>Sub Export_iTunes_XML()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

If Dir(Output, vbNormal) <> "" Then
    Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
End If
If Answer = vbCancel Then Exit Sub

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr
objStream.WriteText "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>" & vbCr

If Sheets("RawMetadata").Range("P4") <> 0 Then Call LocaleTest2

objStream.WriteText "      <production_company>" & Sheets("RawMetadata").Range("H3") & "</production_company>" & vbCr
___________________________________________________________________________
Sub LocaleTest2()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText Sheets("RawMetadata").Range("P4")
objStream.CopyTo Output

End Sub
</code>```

答:
The code would to be like this.

```<code>Sub Export_iTunes_XML()
    Dim vR(), myText As String
    Dim FilePath As String
    Dim FileName As String
    Dim Output As String
    Dim Ws As Worksheet
    Dim n As Long

    FilePath = ActiveWorkbook.Path & "\"
    FileName = "metadata.xml"
    Output = FilePath & FileName
    Set Ws = Sheets("RawMetadata")

    If Dir(Output, vbNormal) <> "" Then
        Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
    End If
    If Answer = vbCancel Then Exit Sub

    n = n + 1
    ReDim Preserve vR(1 To n)
    vR(n) = "<?xml version=""1.0"" encoding=""UTF-8""?>"
    n = n + 1
    ReDim Preserve vR(1 To n)
    vR(n) = "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>"
    With Ws
        If Sheets("RawMetadata").Range("P4") <> 0 Then
            n = n + 1
            ReDim Preserve vR(1 To n)
            vR(n) = .Range("p4")
        End If
        n = n + 1
        ReDim Preserve vR(1 To n)
        vR(n) = "      <production_company>" & .Range("H3") & "</production_company>"
    End With

    myText = Join(vR, vbCrLf)
    TransToUTF8 Output, myText
End Sub
Sub TransToUTF8(myfile As String, str As String)
 Dim objStream As Object
 Set objStream = CreateObject("ADODB.Stream")

    With objStream
        .Charset = "utf-8"
        .Open
        .WriteText str
        .SaveToFile myfile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub
</code>```

Addition

```<code>Sub Export_iTunes_XML()

 Dim XMLFileName As String
 Dim output4 As String
 Dim range4 As Range
 Dim vDB, vR(), vResult()
 Dim i As Long, n As Long, j As Integer
 Dim myText As String

 XMLFileName = "metadata.xml"
 FolderName4 = Sheets("RawMetadata").Range("D42") & "_" & Sheets("iTunes").Range("B8") & ".itmsp"
 FolderPath4 = ActiveWorkbook.Path & "\" & FolderName4

MkDir FolderPath4
output4 = FolderPath4 & "\" & XMLFileName

 vDB = Sheets("iTunes").Range("A1:g936")

For i = 1 To UBound(vDB, 1)
    If vDB(i, 7) = "ON" Then
        ReDim vR(1 To 6)
        For j = 1 To 6
            vR(j) = vDB(i, j)
        Next j
        n = n + 1
        ReDim Preserve vResult(1 To n)
        vResult(n) = Join(vR, "")
    End If
Next i
    myText = Join(vResult, vbCrLf)
    TransToUTF8 output4, myText

 End Sub
</code>```

Body:
So I'm creating a macro to output an UTF-8 encoded XML since the source text will sometimes involve Japanese or Chinese characters. I'm trying to break each section of the XML into different chunks so it's easier for me to edit but my call line isn't working. Since I'm not trained in programming and my knowledge is based on looking up VBA macro codes and tweaking them until I get the desired result, I'm stumped as to how to get my objStream macro to not error when calling another objStream line.

Thanks!

Here it is:

Sub Export_iTunes_XML()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

If Dir(Output, vbNormal) <> "" Then
    Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
End If
If Answer = vbCancel Then Exit Sub

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr
objStream.WriteText "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>" & vbCr

If Sheets("RawMetadata").Range("P4") <> 0 Then Call LocaleTest2

objStream.WriteText "      <production_company>" & Sheets("RawMetadata").Range("H3") & "</production_company>" & vbCr
___________________________________________________________________________
Sub LocaleTest2()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText Sheets("RawMetadata").Range("P4")
objStream.CopyTo Output

End Sub

Body:
The code would to be like this.

Sub Export_iTunes_XML()
    Dim vR(), myText As String
    Dim FilePath As String
    Dim FileName As String
    Dim Output As String
    Dim Ws As Worksheet
    Dim n As Long

    FilePath = ActiveWorkbook.Path & "\"
    FileName = "metadata.xml"
    Output = FilePath & FileName
    Set Ws = Sheets("RawMetadata")

    If Dir(Output, vbNormal) <> "" Then
        Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
    End If
    If Answer = vbCancel Then Exit Sub

    n = n + 1
    ReDim Preserve vR(1 To n)
    vR(n) = "<?xml version=""1.0"" encoding=""UTF-8""?>"
    n = n + 1
    ReDim Preserve vR(1 To n)
    vR(n) = "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>"
    With Ws
        If Sheets("RawMetadata").Range("P4") <> 0 Then
            n = n + 1
            ReDim Preserve vR(1 To n)
            vR(n) = .Range("p4")
        End If
        n = n + 1
        ReDim Preserve vR(1 To n)
        vR(n) = "      <production_company>" & .Range("H3") & "</production_company>"
    End With

    myText = Join(vR, vbCrLf)
    TransToUTF8 Output, myText
End Sub
Sub TransToUTF8(myfile As String, str As String)
 Dim objStream As Object
 Set objStream = CreateObject("ADODB.Stream")

    With objStream
        .Charset = "utf-8"
        .Open
        .WriteText str
        .SaveToFile myfile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub

Addition

Sub Export_iTunes_XML()

 Dim XMLFileName As String
 Dim output4 As String
 Dim range4 As Range
 Dim vDB, vR(), vResult()
 Dim i As Long, n As Long, j As Integer
 Dim myText As String

 XMLFileName = "metadata.xml"
 FolderName4 = Sheets("RawMetadata").Range("D42") & "_" & Sheets("iTunes").Range("B8") & ".itmsp"
 FolderPath4 = ActiveWorkbook.Path & "\" & FolderName4

MkDir FolderPath4
output4 = FolderPath4 & "\" & XMLFileName

 vDB = Sheets("iTunes").Range("A1:g936")

For i = 1 To UBound(vDB, 1)
    If vDB(i, 7) = "ON" Then
        ReDim vR(1 To 6)
        For j = 1 To 6
            vR(j) = vDB(i, j)
        Next j
        n = n + 1
        ReDim Preserve vResult(1 To n)
        vResult(n) = Join(vR, "")
    End If
Next i
    myText = Join(vResult, vbCrLf)
    TransToUTF8 output4, myText

 End Sub


来源: stackexchange

问:
Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)
I have this problem. Chrome continues to return this error

Resource interpreted as stylesheet but transferred with MIME type text/html

The files affected by this error are just the Style, chosen and jquery-gentleselect (other CSS files that are imported in the index in the same way work well and without error). I've already checked my MIME type and text/css is already on CSS.

Honestly I'd like to start by understanding the problem (a thing that seems I cannot do alone).

答:
i was facing the same thing, with sort of the same .htaccess file for making pretty urls. after some hours of looking around and experimenting. i found out that the error was because of relatively linking files.

the browser will start fetching the same source html file for all the css, js and image files, when i would browse a few steps deep into the server.

to counter this you can either use the <base> tag on your html source,

```<code><base href="http://localhost/assets/">
</code>```

and link to files like,

```<code><link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/script.js"></script>
</code>```

or use absolute links for all your files.

```<code><link rel="stylesheet" type="text/css" href="http://localhost/assets/css/style.css" />
<script src="http://localhost/assets/js/script.js"></script>
<img src="http://localhost/assets/images/logo.png" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i was facing the same thing, with sort of the same .htaccess file for making pretty urls. after some hours of looking around and experimenting. i found out that the error was because of relatively linking files.

the browser will start fetching the same source html file for all the css, js and image files, when i would browse a few steps deep into the server.

to counter this you can either use the <base> tag on your html source,

<base href="http://localhost/assets/">

and link to files like,

<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/script.js"></script>

or use absolute links for all your files.

<link rel="stylesheet" type="text/css" href="http://localhost/assets/css/style.css" />
<script src="http://localhost/assets/js/script.js"></script>
<img src="http://localhost/assets/images/logo.png" />


问:
No response when attempting to switch to different view controller in different storyboard
I've got a button on storyboard Alpha that leads to storyboard Beta using the following code:

```<code>@IBAction func showBeta(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Beta", bundle: nil)
    let bvc = storyboard.instantiateViewController(withIdentifier: "BetaViewController") as! BetaViewController

    self.present(bvc, animated: true, completion: nil)
}
</code>```

This works without any problems.

However, I ran into the issue of not having a back button in Beta because self.present makes the new view appear modally.

I then read this post where the poster had the same problem as me. The answer suggested this code:

```<code>self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)
</code>```

So I changed my code to:

```<code>@IBAction func showBeta(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Beta", bundle: nil)
    let bvc = storyboard.instantiateViewController(withIdentifier: "BetaViewController") as! BetaViewController

    self.navigationController?.pushViewController(bvc, animated: true)
}
</code>```

However, now nothing happens at all when clicking the button. No errors, nothing. What's going on here?

答:
It seems your AlphaViewController isn't embedded in a UINavigationController.

Try this piece of code:

```<code>@IBAction func showBeta(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Beta", bundle: nil)
    let bvc = storyboard.instantiateViewController(withIdentifier: "BetaViewController") as! BetaViewController

    show(bvc, sender: self)
}
</code>```

This will cause your BetaViewController appear modally if your AlphaViewController isn't embedded in navigation controller and you won't get the back button. But if your AlphaViewController is embedded in navigation controller then your BetaViewController will be shown as left-to-right transition and you will get your desired back button.

To add navigation controller:

If you added your AlphaViewController from interface builder, follow this to embed it in a navigation controller: SelectAlphaViewController -> Editor -> Embed In -> Navigation Controller

Or, if you added your controller programmatically, you can check this answer.

Body:
I've got a button on storyboard Alpha that leads to storyboard Beta using the following code:

@IBAction func showBeta(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Beta", bundle: nil)
    let bvc = storyboard.instantiateViewController(withIdentifier: "BetaViewController") as! BetaViewController

    self.present(bvc, animated: true, completion: nil)
}

This works without any problems.

However, I ran into the issue of not having a back button in Beta because self.present makes the new view appear modally.

I then read this post where the poster had the same problem as me. The answer suggested this code:

self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)

So I changed my code to:

@IBAction func showBeta(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Beta", bundle: nil)
    let bvc = storyboard.instantiateViewController(withIdentifier: "BetaViewController") as! BetaViewController

    self.navigationController?.pushViewController(bvc, animated: true)
}

However, now nothing happens at all when clicking the button. No errors, nothing. What's going on here?

Body:
It seems your AlphaViewController isn't embedded in a UINavigationController.

Try this piece of code:

@IBAction func showBeta(_ sender: Any) {

    let storyboard = UIStoryboard(name: "Beta", bundle: nil)
    let bvc = storyboard.instantiateViewController(withIdentifier: "BetaViewController") as! BetaViewController

    show(bvc, sender: self)
}

This will cause your BetaViewController appear modally if your AlphaViewController isn't embedded in navigation controller and you won't get the back button. But if your AlphaViewController is embedded in navigation controller then your BetaViewController will be shown as left-to-right transition and you will get your desired back button.

To add navigation controller:

If you added your AlphaViewController from interface builder, follow this to embed it in a navigation controller: SelectAlphaViewController -> Editor -> Embed In -> Navigation Controller

Or, if you added your controller programmatically, you can check this answer.


问:
Using external properties file with Springs as init.d service
I am trying to run a Spring-Boot application as a init.d linux service using this method provided by Spring. While the service will successfully run with

```<code>service vxmonitor start RUN_ARGS=--spring.config.location=/var/vxmonitor/config.properties
</code>```

the external properties file will not load. The properties file is located in the same folder as the jar file. If I run the application using

```<code>java -jar monitor-0.0.1-SNAPSHOT.jar --spring.config.location=config.properties
</code>```

the external properties loads fine.

My question is how to get the Springs service to point to the external config file, and if that is possible, how to integrate the location of the external config file into the service itself so RUN_ARGS doesnt need to be specified. Not sure what files would be helpful to help solve this problem.

config.properties

```<code>server.port=8099
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.valgoix</groupId>
<artifactId>monitor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>vlgx-monitoring-svc</name>
<description>Client side server monitoring web service</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.2-1003-jdbc4</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

If there is another file needed please tell me. Thank you

EDIT:
I attempted to modify the service created by changing

```<code>arguments=(-Dsun.misc.URLClassPath.disableJarChecking=true $JAVA_OPTS -jar "$jarfile" $RUN_ARGS "$@")
</code>```

to

```<code>arguments=(-Dsun.misc.URLClassPath.disableJarChecking=true $JAVA_OPTS -jar "$jarfile" --spring.config.location=/var/vxmonitor/config.properties $RUN_ARGS "$@")
</code>```

except when I run the service I get the error

```<code>Error: Invalid or corrupt jarfile /var/vxmonitor/vxmonitor.jar
</code>```

written in the log file.

答:
You need to use a file URL as follows for spring.config.location:

--spring.config.location=file:///var/vxmonitor/config.properties

Body:
I am trying to run a Spring-Boot application as a init.d linux service using this method provided by Spring. While the service will successfully run with

service vxmonitor start RUN_ARGS=--spring.config.location=/var/vxmonitor/config.properties

the external properties file will not load. The properties file is located in the same folder as the jar file. If I run the application using

java -jar monitor-0.0.1-SNAPSHOT.jar --spring.config.location=config.properties

the external properties loads fine.

My question is how to get the Springs service to point to the external config file, and if that is possible, how to integrate the location of the external config file into the service itself so RUN_ARGS doesnt need to be specified. Not sure what files would be helpful to help solve this problem.

config.properties

server.port=8099

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.valgoix</groupId>
<artifactId>monitor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>vlgx-monitoring-svc</name>
<description>Client side server monitoring web service</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.2-1003-jdbc4</version>
    </dependency>
</dependencies>

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

If there is another file needed please tell me. Thank you

EDIT:
I attempted to modify the service created by changing

arguments=(-Dsun.misc.URLClassPath.disableJarChecking=true $JAVA_OPTS -jar "$jarfile" $RUN_ARGS "$@")

to

arguments=(-Dsun.misc.URLClassPath.disableJarChecking=true $JAVA_OPTS -jar "$jarfile" --spring.config.location=/var/vxmonitor/config.properties $RUN_ARGS "$@")

except when I run the service I get the error

Error: Invalid or corrupt jarfile /var/vxmonitor/vxmonitor.jar

written in the log file.


问:
Remove netstat output (specifically Not all processes could be identified line)
I'm having trouble removing the output from the netstat command when I check if a current port is being used. I dont need the output of the command but rather just the error code.

Running netstat -anp | grep 1521 &>/dev/null results in

```<code>(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
</code>```

being shown as the output. I have also tried:

```<code>2>/dev/null| cut -d' ' -f45-50 | sed 's/[^0-9]*//g'
</code>```

which just results in a bunch of empty lines after the Not all processes... output but still displays that in the output.

答:
The accepted answer doesn't work for me, CentOS6.5 32bit here. It outputs nothing no matter what state the port is.

I found my solution:

```<code>netstat -antp 2>/dev/null | grep [port-num]
</code>```

This will omit the first two lines of netstat if it is executed by regular user.

The warning two lines needed to be omitted:

```<code>(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
</code>```

and works for two situations:

the port is "LISTEN" state

the port is "TIME_WAIT" state.

Body:
I'm having trouble removing the output from the netstat command when I check if a current port is being used. I dont need the output of the command but rather just the error code.

Running netstat -anp | grep 1521 &>/dev/null results in

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)

being shown as the output. I have also tried:

2>/dev/null| cut -d' ' -f45-50 | sed 's/[^0-9]*//g'

which just results in a bunch of empty lines after the Not all processes... output but still displays that in the output.

Body:
The accepted answer doesn't work for me, CentOS6.5 32bit here. It outputs nothing no matter what state the port is.

I found my solution:

netstat -antp 2>/dev/null | grep [port-num]

This will omit the first two lines of netstat if it is executed by regular user.

The warning two lines needed to be omitted:

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)

and works for two situations:

the port is "LISTEN" state

the port is "TIME_WAIT" state.


问:
Webpack not found when app deployed to Heroku
I'm getting the error sh: 1: webpack: not found when the app is deployed to production. I've tried moving all the dependencies related to webpack from the devDependency list to the dependency list in the package.json file to avail. The Heroku error log can be seen here for greater insight. What steps could be taken to solve this issue?

答:
You are assuming 'webpack' is installed as a global package in your heroku environment.

Run webpack directly from your node_modules to avoid having to install it globally, like so...

package.json:

```<code>{
  ...
  "scripts": {
    "build": "node node_modules/webpack/bin/webpack.js --display-error-details",
    ...
  }
  ...
}
</code>```

Body:
You are assuming 'webpack' is installed as a global package in your heroku environment.

Run webpack directly from your node_modules to avoid having to install it globally, like so...

package.json:

{
  ...
  "scripts": {
    "build": "node node_modules/webpack/bin/webpack.js --display-error-details",
    ...
  }
  ...
}


问:
Library (dylib) not loaded - image not found - Python IDE
Basically I'm trying to run some Python code from savReaderWriter module in order to create a .sav file ready to open in IBM SPSS. As a macOS user I needed to run these two lines in the terminal first for the module to work:

```<code>echo 'export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/spssio/macos'  >> ~/.bash_profile
echo 'export LC_ALL=en_US.UTF-8'  >> ~/.bash_profile
</code>```

Below you can see a piece of code I'm trying to run in Python:

```<code>import savReaderWriter

savFileName = "someFile.sav"
records = [['Test1', 1, 1], ['Test2', 2, 1]]
varNames = ['var1', 'v2', 'v3']
varTypes = {'var1': 5, 'v2': 0, 'v3': 0}
with savReaderWriter.SavWriter(savFileName, varNames, varTypes, ioUtf8=True) as writer:
    for record in records:
        writer.writerow(record)
</code>```

My problem is that while running the code in Python through terminal.app works like a charm and a new .sav file appears, trying to execute the very same code in an IDE (tried PyCharm and Spyder) gives me an error:

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2847, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-94007b092d47>", line 7, in <module>
    with savReaderWriter.SavWriter(savFileName, varNames, varTypes, ioUtf8=True) as writer:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/savWriter.py", line 198, in __init__
    super(Header, self).__init__(savFileName, ioUtf8, ioLocale)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 29, in __init__
    self.spssio = self.loadLibrary()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 117, in loadLibrary
    spssio = self._loadLibs("macos")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 89, in _loadLibs
    return [load(os.path.join(path, lib)) for lib in libs][-1]
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 89, in <listcomp>
    return [load(os.path.join(path, lib)) for lib in libs][-1]
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ctypes/__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/spssio/macos/libicuuc48.1.dylib, 6): Library not loaded: @executable_path/../lib/libicudata48.1.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/spssio/macos/libicuuc48.1.dylib
  Reason: image not found
</code>```

The module author was unable to help me on this matter, therefore I would be very glad for any suggestions from this community.

EDIT (added sys.path):

From terminal:

```<code> ['',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages',
 '/Users/mg/mne-python']
</code>```

From IDE:

```<code>['/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Users/mg/Documents/Python/Projects/MD',
 '/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages',
 '/Users/mg/mne-python',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/extensions',
 '/Users/mg/Documents/Python/Projects/MD']
</code>```

Regards,

MG

答:
I am not a Mac person, but are you really using Python 3.6?  Does the savReaderWriter support that version?  I doubt that the I/o module it uses is built for that version.

If this works via Terminal but not an IDE, check that the Python search paths are the same.

Body:
Basically I'm trying to run some Python code from savReaderWriter module in order to create a .sav file ready to open in IBM SPSS. As a macOS user I needed to run these two lines in the terminal first for the module to work:

echo 'export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/spssio/macos'  >> ~/.bash_profile
echo 'export LC_ALL=en_US.UTF-8'  >> ~/.bash_profile

Below you can see a piece of code I'm trying to run in Python:

import savReaderWriter

savFileName = "someFile.sav"
records = [['Test1', 1, 1], ['Test2', 2, 1]]
varNames = ['var1', 'v2', 'v3']
varTypes = {'var1': 5, 'v2': 0, 'v3': 0}
with savReaderWriter.SavWriter(savFileName, varNames, varTypes, ioUtf8=True) as writer:
    for record in records:
        writer.writerow(record)

My problem is that while running the code in Python through terminal.app works like a charm and a new .sav file appears, trying to execute the very same code in an IDE (tried PyCharm and Spyder) gives me an error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2847, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-94007b092d47>", line 7, in <module>
    with savReaderWriter.SavWriter(savFileName, varNames, varTypes, ioUtf8=True) as writer:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/savWriter.py", line 198, in __init__
    super(Header, self).__init__(savFileName, ioUtf8, ioLocale)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 29, in __init__
    self.spssio = self.loadLibrary()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 117, in loadLibrary
    spssio = self._loadLibs("macos")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 89, in _loadLibs
    return [load(os.path.join(path, lib)) for lib in libs][-1]
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/generic.py", line 89, in <listcomp>
    return [load(os.path.join(path, lib)) for lib in libs][-1]
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ctypes/__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/spssio/macos/libicuuc48.1.dylib, 6): Library not loaded: @executable_path/../lib/libicudata48.1.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/savReaderWriter/spssio/macos/libicuuc48.1.dylib
  Reason: image not found

The module author was unable to help me on this matter, therefore I would be very glad for any suggestions from this community.

EDIT (added sys.path):

From terminal:

 ['',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages',
 '/Users/mg/mne-python']

From IDE:

['/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Users/mg/Documents/Python/Projects/MD',
 '/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages',
 '/Users/mg/mne-python',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/extensions',
 '/Users/mg/Documents/Python/Projects/MD']

Regards,

MG


问:
How to find a float in a string - Python?
I want to find the first float that appears in a string using Python 3.

I looked at other similar questions but I couldn't understand them and when I tried to implement them they didn't work for my case.

An example string would be

I would like 1.5 cookies please

答:
I'm pretty sure there's more elegant solution, but this one works for your specific case:</p>
```<code>s = 'I would like 1.5 cookies please'

for i in s.split():
    try:
        #trying to convert i to float
        result = float(i)
        #break the loop if i is the first string that's successfully converted
        break
    except:
        continue

print(result) #1.5
</code>```

Body:
I'm pretty sure there's more elegant solution, but this one works for your specific case:

s = 'I would like 1.5 cookies please'

for i in s.split():
    try:
        #trying to convert i to float
        result = float(i)
        #break the loop if i is the first string that's successfully converted
        break
    except:
        continue

print(result) #1.5

ContentLicense: CC BY-SA 4.0


答:
You can find this using regex, notice this pattern will only return the substring if it's already in float type, i.e. decimal fomatting, so something like this:

```<code>>>> import re
>>> matches = re.findall("[+-]?\d+\.\d+", "I would like 1.5 cookies please")
</code>```

As you say you want only the first one:

```<code>>>> matches[0]
'1.5'
</code>```

Edit: Added [+-]? to the pattern for it to recognize negative floats, as pistache recommended!

Title: How to find a float in a string - Python?

Body:
I want to find the first float that appears in a string using Python 3.

I looked at other similar questions but I couldn't understand them and when I tried to implement them they didn't work for my case.

An example string would be

I would like 1.5 cookies please

Body:
You can find this using regex, notice this pattern will only return the substring if it's already in float type, i.e. decimal fomatting, so something like this:

>>> import re
>>> matches = re.findall("[+-]?\d+\.\d+", "I would like 1.5 cookies please")

As you say you want only the first one:

>>> matches[0]
'1.5'

Edit: Added [+-]? to the pattern for it to recognize negative floats, as pistache recommended!


问:
Set negative margin on View programmatically
I know how to set margins of a View programmatically with LinearLayout.LayoutParams and the method setMargins(int, int, int, int) but how can I put a negative margin on a view?

答:
Using math seems to trick it enough for me.</p>

```<code> ViewGroup.MarginLayoutParams params =
     (ViewGroup.MarginLayoutParams)view.getLayoutParams();
 params.topMargin = 100 - 200;   // -100
</code>```

Body:
Using math seems to trick it enough for me.

 ViewGroup.MarginLayoutParams params =
     (ViewGroup.MarginLayoutParams)view.getLayoutParams();
 params.topMargin = 100 - 200;   // -100


问:
How to create the checkBox in circular shape?
I am facing the issue in creating the checkbox in circular shape in android. I tried many methods but my problem is not solved.I created the shapes and applied to the checkbox then also problem is not solved.Please help me how to create the check box in circle shape .

How to create the circular checkbox like shown image.

答:
Solution accepted is correct, but following the same flow you can change the shapes to use a drawable on the "checked.xml" this solution should work with android devices before API 21 because there is no width or height on shapes on xml drawables.

Unchecked XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

        <solid android:color = "@color/lightgray" />
</shape>
</code>```

Checked XML:

```<code><?xml version="1.0" encoding="utf-8"?>
      <layer-list xmlns:android = "http://schemas.android.com/apk/res/android">
            <item>
                <shape android:shape="oval">
                    <solid android:color="@color/colorPrimary" />
                </shape>
                </item>

            <item
                         android:drawable="@drawable/check_arrow_png" />
        </layer-list>
</code>```

Body:
Solution accepted is correct, but following the same flow you can change the shapes to use a drawable on the "checked.xml" this solution should work with android devices before API 21 because there is no width or height on shapes on xml drawables.

Unchecked XML:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

        <solid android:color = "@color/lightgray" />
</shape>

Checked XML:

<?xml version="1.0" encoding="utf-8"?>
      <layer-list xmlns:android = "http://schemas.android.com/apk/res/android">
            <item>
                <shape android:shape="oval">
                    <solid android:color="@color/colorPrimary" />
                </shape>
                </item>

            <item
                         android:drawable="@drawable/check_arrow_png" />
        </layer-list>


问:
Get the content of siblings elements with jQuery
I need to get the content of some specific elements using jquery, the problem is that i have the same element repeating on my page:

```<code><div class="content">
   <img alt="" src="">
   <p class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
   <p class="info">Lorem ipsum dolor...</p>
   <ul>
     <li><a class="uiButton">Test</a></li>
   </ul>
 </div>
</code>```

So, the div.content repeat on my page many times and I want to get only the contents of the div that holds the button was clicked. I've added a onclick event on the .uiButton and tried to use parent(".txt") or siblings(".txt"), but dont seems to work...

```<code>$(".uiButton").click(function(){
  var txt = $(this).parent(".txt").text();
}
</code>```

答:
You need to go up to the wrapper and down, you can go to siblings, but in this case it will be harder.</p>

```<code>$(".uiButton").click(function(){
  var txt = $(this).closest('.content').find('.txt').text();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to get the content of some specific elements using jquery, the problem is that i have the same element repeating on my page:

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor...

Test

So, the div.content repeat on my page many times and I want to get only the contents of the div that holds the button was clicked. I've added a onclick event on the .uiButton and tried to use parent(".txt") or siblings(".txt"), but dont seems to work...

$(".uiButton").click(function(){
  var txt = $(this).parent(".txt").text();
}

Body:
You need to go up to the wrapper and down, you can go to siblings, but in this case it will be harder.

$(".uiButton").click(function(){
  var txt = $(this).closest('.content').find('.txt').text();
}


问:
Message Manager Broken
I'm trying to write a simple Message Manager, but none of my messages are showing up in my queue.

The code that calls it is:

```<code>//initialize message manager
    CJournal.Journal(Main.class, "Initializing message manager");
    MessageManager messageManager = new MessageManager();
    messageManager.run();

    //send bootstrap message
    CJournal.Journal(Main.class, "Testing messanger: ending bootstrapping message to messagemanager");
    Message boot_strap_message = new Message();
    boot_strap_message.mflag = EEventMachine.EM_BOOTSTRAP;
    messageManager.EnqueueMessage(boot_strap_message);
</code>```

And the message manager code is:

```<code>public  class MessageManager implements Runnable {

    PriorityQueue<Message> messagesQueue = new PriorityQueue<Message>();

    public void EnqueueMessage(Message message)
    {
        messagesQueue.add(message);
    }

    @Override
    public  void run() {
        // TODO Auto-generated method stub
        while (true)
        {
            //pull message from queue

            if (!messagesQueue.isEmpty())
            {
                CJournal.Journal(MessageManager.class, "Found a message");
                Message message = messagesQueue.remove();

                //dispatch messages according to their type
                switch(message.mflag)
                {
                case EM_BOOTSTRAP:
                    CJournal.Journal(MessageManager.class, "Messaging system working properly.");
                default:
                    CJournal.Journal(MessageManager.class, "Dispatch Message Trashed");
                }
            }
        }
    }
</code>```

And the debug output is:

```<code>13 In Class::class Sampler.Main Journal Entry:Testing Event Manager
14 In Class::class Sampler.Main Journal Entry:Created dummy CEvent. Pushing to event manager.
15 In Class::class Sampler.Main Journal Entry:Initializing message manager
</code>```

I should be getting, "Messaging System working properly"

Any ideas?

```<code>--------------------------------------------------------------
O`11 In Class::class SchedulingManager.Timer.CTimerManager Journal Entry:Creating a CTimer Object
12 In Class::class SchedulingManager.Timer.CTimerManager Journal Entry:Timer creation success. Adding CTimer object to internal list Of Timers
13 In Class::class Sampler.Main Journal Entry:Testing Event Manager
14 In Class::class Sampler.Main Journal Entry:Created dummy CEvent. Pushing to event manager.
15 In Class::class Sampler.Main Journal Entry:Initializing message manager
16 In Class::class Sampler.Main Journal Entry:Testing messanger: ending bootstrapping message to messagemanager
Exception in thread "main" Exception in thread "Thread-4" java.lang.ClassCastException: MessageManagement.Message cannot be cast to java.lang.Comparable
    at java.util.concurrent.PriorityBlockingQueue.siftUpComparable(Unknown Source)
    at java.util.concurrent.PriorityBlockingQueue.offer(Unknown Source)
    at java.util.concurrent.PriorityBlockingQueue.add(Unknown Source)
    at MessageManagement.MessageManager.EnqueueMessage(MessageManager.java:69)
    at Sampler.Main.main(Main.java:128)
java.util.NoSuchElementException
    at java.util.AbstractQueue.remove(Unknown Source)
    at MessageManagement.MessageManager.run(MessageManager.java:47)
</code>```

And this code:

`public  class MessageManager extends Thread {

```<code>    @Override
    public  void run() {
        // TODO Auto-generated method stub
        while (true)
        {

            if (!messagesQueue.isEmpty())
            {
                //pull message from queue
                Message message = messagesQueue.remove();

                //dispatch messages according to their type
                switch(message.mflag)
                {
                case EM_BOOTSTRAP:
                    CJournal.Journal(MessageManager.class, "Messaging system working properly.");
                default:
                    CJournal.Journal(MessageManager.class, "Dispatch Message Trashed");
                }
            }
        }
    }

    public static PriorityBlockingQueue<Message> messagesQueue = new PriorityBlockingQueue<Message>();

    public static void EnqueueMessage(Message message)
    {
        messagesQueue.add(message);
    }
</code>```

And this is how I am declaring my thread:

```<code>    MessageManager messageManager = new MessageManager();
    messageManager.start();

    //send bootstrap message
    CJournal.Journal(Main.class, "Testing messanger: ending bootstrapping message to messagemanager");
    Message boot_strap_message = new Message();
    boot_strap_message.mflag = EEventMachine.EM_BOOTSTRAP;
    messageManager.EnqueueMessage(boot_strap_message);

    Loop loop = new Loop();  //hand over to game loop
</code>```

I'm not sure what the problem is.

答:
You are calling run() on your MessageManager from within the same Thread which then goes into an infinite loop.

You need to wrap your MessageManager in a new Thread and start that thread.

```<code>new Thread(messageManager).start();
</code>```

However you may need to change your PriorityQueue if you are going to access it from multiple threads

From JavaDoc:

Note that this implementation is not synchronized. Multiple threads should not access a PriorityQueue instance concurrently if any of the threads modifies the queue. Instead, use the thread-safe PriorityBlockingQueue class.

Title: Message Manager Broken

Body:
I'm trying to write a simple Message Manager, but none of my messages are showing up in my queue.

The code that calls it is:

//initialize message manager
    CJournal.Journal(Main.class, "Initializing message manager");
    MessageManager messageManager = new MessageManager();
    messageManager.run();

    //send bootstrap message
    CJournal.Journal(Main.class, "Testing messanger: ending bootstrapping message to messagemanager");
    Message boot_strap_message = new Message();
    boot_strap_message.mflag = EEventMachine.EM_BOOTSTRAP;
    messageManager.EnqueueMessage(boot_strap_message);

And the message manager code is:

public  class MessageManager implements Runnable {

    PriorityQueue<Message> messagesQueue = new PriorityQueue<Message>();

    public void EnqueueMessage(Message message)
    {
        messagesQueue.add(message);
    }

    @Override
    public  void run() {
        // TODO Auto-generated method stub
        while (true)
        {
            //pull message from queue

            if (!messagesQueue.isEmpty())
            {
                CJournal.Journal(MessageManager.class, "Found a message");
                Message message = messagesQueue.remove();

                //dispatch messages according to their type
                switch(message.mflag)
                {
                case EM_BOOTSTRAP:
                    CJournal.Journal(MessageManager.class, "Messaging system working properly.");
                default:
                    CJournal.Journal(MessageManager.class, "Dispatch Message Trashed");
                }
            }
        }
    }

And the debug output is:

13 In Class::class Sampler.Main Journal Entry:Testing Event Manager
14 In Class::class Sampler.Main Journal Entry:Created dummy CEvent. Pushing to event manager.
15 In Class::class Sampler.Main Journal Entry:Initializing message manager

I should be getting, "Messaging System working properly"

Any ideas?

--------------------------------------------------------------
O`11 In Class::class SchedulingManager.Timer.CTimerManager Journal Entry:Creating a CTimer Object
12 In Class::class SchedulingManager.Timer.CTimerManager Journal Entry:Timer creation success. Adding CTimer object to internal list Of Timers
13 In Class::class Sampler.Main Journal Entry:Testing Event Manager
14 In Class::class Sampler.Main Journal Entry:Created dummy CEvent. Pushing to event manager.
15 In Class::class Sampler.Main Journal Entry:Initializing message manager
16 In Class::class Sampler.Main Journal Entry:Testing messanger: ending bootstrapping message to messagemanager
Exception in thread "main" Exception in thread "Thread-4" java.lang.ClassCastException: MessageManagement.Message cannot be cast to java.lang.Comparable
    at java.util.concurrent.PriorityBlockingQueue.siftUpComparable(Unknown Source)
    at java.util.concurrent.PriorityBlockingQueue.offer(Unknown Source)
    at java.util.concurrent.PriorityBlockingQueue.add(Unknown Source)
    at MessageManagement.MessageManager.EnqueueMessage(MessageManager.java:69)
    at Sampler.Main.main(Main.java:128)
java.util.NoSuchElementException
    at java.util.AbstractQueue.remove(Unknown Source)
    at MessageManagement.MessageManager.run(MessageManager.java:47)

And this code:

`public  class MessageManager extends Thread {

    @Override
    public  void run() {
        // TODO Auto-generated method stub
        while (true)
        {

            if (!messagesQueue.isEmpty())
            {
                //pull message from queue
                Message message = messagesQueue.remove();

                //dispatch messages according to their type
                switch(message.mflag)
                {
                case EM_BOOTSTRAP:
                    CJournal.Journal(MessageManager.class, "Messaging system working properly.");
                default:
                    CJournal.Journal(MessageManager.class, "Dispatch Message Trashed");
                }
            }
        }
    }

    public static PriorityBlockingQueue<Message> messagesQueue = new PriorityBlockingQueue<Message>();

    public static void EnqueueMessage(Message message)
    {
        messagesQueue.add(message);
    }

And this is how I am declaring my thread:

    MessageManager messageManager = new MessageManager();
    messageManager.start();

    //send bootstrap message
    CJournal.Journal(Main.class, "Testing messanger: ending bootstrapping message to messagemanager");
    Message boot_strap_message = new Message();
    boot_strap_message.mflag = EEventMachine.EM_BOOTSTRAP;
    messageManager.EnqueueMessage(boot_strap_message);

    Loop loop = new Loop();  //hand over to game loop

I'm not sure what the problem is.

Body:
You are calling run() on your MessageManager from within the same Thread which then goes into an infinite loop.

You need to wrap your MessageManager in a new Thread and start that thread.

new Thread(messageManager).start();

However you may need to change your PriorityQueue if you are going to access it from multiple threads

From JavaDoc:

Note that this implementation is not synchronized. Multiple threads should not access a PriorityQueue instance concurrently if any of the threads modifies the queue. Instead, use the thread-safe PriorityBlockingQueue class.


问:
Connect a signal to the slot of a QMetaProperty
I'm not sure if something like this is possible, but I am attempting to dynamically generate a GUI based on properties that have been registered into Qt's property system. My assumption is that since I have registered a property using Q_PROPERTY() in this fashion:

```<code>Q_PROPERTY(propertyType propertyName WRITE setPropertyName READ getPropertyName NOTIFY propertynameSignal)
</code>```

I should be able to retrieve the signature of the write or read functions for connection using the connect() function. The goal of this is to have a dialog connected to this object for modifying properties, but without having to hand write all of it. Is this possible, am going about it the wrong way, or should I just hardcode the dialog?

EDIT 1:
I'll share some of the code (stripped down) I have which will hopefully make it more obvious as to what I'm trying to do:

Class declaration for particular class:

```<code>class MyObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool someBool READ getBool WRITE setBool)
  public:
    bool someBool;

    bool getBool();
    void setBool(bool);
}
</code>```

QDialog subclass that points to this Object:

```<code>void MyDialog::generateUI()
{
    const QMetaObject* metaObject = _MyObjectPtr->metaObject();
    for (int i = 0; i < metaObject->propertyCount(); ++i)
    {
        QMetaProperty property = metaObject->property(i);
        if (!strcmp(property.typeName(), "bool")
        {
            QCheckBox* checkBox = new QCheckBox(this);
            bool state = metaObject->property(property->name()).toBool();
            checkBox->setCheckState((state) ? Qt::Checked : Qt::Unchecked);

            // Add checkBox to QDialog layout widgets here
        }
    }
}
</code>```

Forgive all the My* renamings, but I need to keep my actual class/member names private.

I can confirm that the object pointed to by MyObjectPtr is being read from properly, because the starting values reflect values that I expect when I change them around. The trouble is connecting this back to that object. I can change the values inside the checkbox GUI-side, but the values aren't being sent to the actual object pointed to by _MyObjectPtr.

答:
I also had some thoughts about automatic UI generation based on QObject properties. But at the moment I don't work in this direction because usually, I need specific UI layout in order to make it a little bit user-friendly.

While I have nothing to say about automatic UI generation, I have something for automatic UI binding. The code is not perfect and a bit hard-coded, but the main idea is visible. I think that something like this may also be used for automatic UI generation.

Body:
I'm not sure if something like this is possible, but I am attempting to dynamically generate a GUI based on properties that have been registered into Qt's property system. My assumption is that since I have registered a property using Q_PROPERTY() in this fashion:

Q_PROPERTY(propertyType propertyName WRITE setPropertyName READ getPropertyName NOTIFY propertynameSignal)

I should be able to retrieve the signature of the write or read functions for connection using the connect() function. The goal of this is to have a dialog connected to this object for modifying properties, but without having to hand write all of it. Is this possible, am going about it the wrong way, or should I just hardcode the dialog?

EDIT 1:
I'll share some of the code (stripped down) I have which will hopefully make it more obvious as to what I'm trying to do:

Class declaration for particular class:

class MyObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool someBool READ getBool WRITE setBool)
  public:
    bool someBool;

    bool getBool();
    void setBool(bool);
}

QDialog subclass that points to this Object:

void MyDialog::generateUI()
{
    const QMetaObject* metaObject = _MyObjectPtr->metaObject();
    for (int i = 0; i < metaObject->propertyCount(); ++i)
    {
        QMetaProperty property = metaObject->property(i);
        if (!strcmp(property.typeName(), "bool")
        {
            QCheckBox* checkBox = new QCheckBox(this);
            bool state = metaObject->property(property->name()).toBool();
            checkBox->setCheckState((state) ? Qt::Checked : Qt::Unchecked);

            // Add checkBox to QDialog layout widgets here
        }
    }
}

Forgive all the My* renamings, but I need to keep my actual class/member names private.

I can confirm that the object pointed to by MyObjectPtr is being read from properly, because the starting values reflect values that I expect when I change them around. The trouble is connecting this back to that object. I can change the values inside the checkbox GUI-side, but the values aren't being sent to the actual object pointed to by _MyObjectPtr.


问:
Group Bar Chart with Seaborn/Matplotlib
My goal is to create a grouped bar chart like the one below, using a pandas DataFrame that is grouped by two variables "Alpha" and "Beta."

```<code>xl2 = xl.groupby(['Alpha','Beta']).median()
</code>```

When I tried this, a KeyError was thrown on 'Alpha'

```<code>import seaborn as sns
sns.barplot(x=['Alpha', 'Beta'], y=xl2['Gamma'])
</code>```

My hope was to pass in a list of x values to index on ('Alpha' and 'Beta'), and graph the associated 'Gamma." The documentation for the seaborn.barplot function doesn't provide any group bar chart examples.

Thanks for your help!

答:
Altair can be helpful in such cases. Here is the plot produced by the following code.

Imports

```<code>import pandas as pd
import numpy as np
from altair import *
</code>```

Generating dataset

```<code>np.random.seed(0)
df = pd.DataFrame({
    "x": np.random.choice(range(0, 5), 250),
    "w": np.random.uniform(50, 400, 250),
    "cat": np.random.choice(["A", "B", "C", "D", "E"], 250)
})
</code>```

Plotting

```<code>Chart(df).mark_bar().encode(x=X('cat', axis=False),
                            y=Y('median(w)', axis=Axis(grid=False)),
                            color='cat',
                            column=Column('x', axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),scale=Scale(padding=30.0)),
                        ).configure_facet_cell( strokeWidth=0.0).configure_cell(width=200, height=200)
</code>```

The key things in the altair code are:

X values are categories ('cat' in the df)

Color is by category

Y values are by median of the variable

Different columns represent different years

Title: Group Bar Chart with Seaborn/Matplotlib

Body:
My goal is to create a grouped bar chart like the one below, using a pandas DataFrame that is grouped by two variables "Alpha" and "Beta."

xl2 = xl.groupby(['Alpha','Beta']).median()

When I tried this, a KeyError was thrown on 'Alpha'

import seaborn as sns
sns.barplot(x=['Alpha', 'Beta'], y=xl2['Gamma'])

My hope was to pass in a list of x values to index on ('Alpha' and 'Beta'), and graph the associated 'Gamma." The documentation for the seaborn.barplot function doesn't provide any group bar chart examples.

Thanks for your help!

Body:
Altair can be helpful in such cases. Here is the plot produced by the following code.

Imports

import pandas as pd
import numpy as np
from altair import *

Generating dataset

np.random.seed(0)
df = pd.DataFrame({
    "x": np.random.choice(range(0, 5), 250),
    "w": np.random.uniform(50, 400, 250),
    "cat": np.random.choice(["A", "B", "C", "D", "E"], 250)
})

Plotting

Chart(df).mark_bar().encode(x=X('cat', axis=False),
                            y=Y('median(w)', axis=Axis(grid=False)),
                            color='cat',
                            column=Column('x', axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),scale=Scale(padding=30.0)),
                        ).configure_facet_cell( strokeWidth=0.0).configure_cell(width=200, height=200)

The key things in the altair code are:

X values are categories ('cat' in the df)

Color is by category

Y values are by median of the variable

Different columns represent different years


问:
Simplest way to go about transforming data from kafka
I am working on a project that pulls data from multiple db sources using kafka connect. I want to then be able to transform the data into a specified json format and then finally push that final json to an S3 bucket preferably using kafka connect to keep my overhead down.

Here is an example of what the data currently looks like coming into kafka (in avro format):

```<code>{"tableName":"TABLE1","SchemaName{"string":"dbo"},"tableID":1639117030,"columnName":{"string":"DATASET"},"ordinalPosition":{"int":1},"isNullable":{"int":1},"dataType":{"string":"varchar"},"maxLength":{"int":510},"precision":{"int":0},"scale":{"int":0},"isPrimaryKey":{"int":0},"tableSizeKB":{"long":72}}
{"tableName":"dtproperties","SchemaName":{"string":"dbo"},"tableID":1745441292,"columnName":{"string":"id"},"ordinalPosition":{"int":1},"isNullable":{"int":0},"dataType":{"string":"int"},"maxLength":{"int":4},"precision":{"int":10},"scale":{"int":0},"isPrimaryKey":{"int":1},"tableSizeKB":{"long":24}}
</code>```

This looks like so when converted to JSON:

```<code>{
      "tablename" : "AS_LOOKUPS",
      "tableID": 5835333,
      "columnName": "SVALUE",
      "ordinalPosition": 6,
      "isNullable": 1,
      "dataType": "varchar",
      "maxLength": 4000,
      "precision": 0,
      "scale": 0,
      "isPrimaryKey": 0,
      "tableSize": 0,
      "sizeUnit": "GB"
},
{
      "tablename" : "AS_LOOKUPS",
      "tableID": 5835333,
      "columnName": "SORT_ORDER",
      "ordinalPosition": 7,
      "isNullable": 1,
      "dataType": "int",
      "maxLength": 4,
      "precision": 10,
      "scale": 0,
      "isPrimaryKey": 0,
      "tableSize": 0,
      "sizeUnit": "GB"
}
</code>```

My goal is to get the data to look like so:

```<code>{
  "header": "Database Inventory",
  "DBName": "DB",
  "ServerName": "server@server.com",
  "SchemaName": "DBE",
  "DB Owner": "Name",
  "DB Guardian" : "Name/Group",
  "ASV" : "ASVC1AUTODWH",
  "ENVCI": "ENVC1AUTODWHORE",
  "Service Owner" : "Name/Group",
  "Business Owner" : "Name/Group",
  "Support Owner" : "Name/Group",
  "Date of Data" : "2017-06-28 12:12:55.000",
  "TABLE_METADATA": {
  "TABLE_SIZE" : "500",
  "UNIT_SIZE" : "GB",
  "TABLE_ID": 117575457,
  "TABLE_NAME": "spt_fallback_db",
  "COLUMN_METADATA": [
  {
    "COLUMN_NM": "xserver_name",
    "DATE_TYPE": "varchar",
    "MAX_LENGTH": 30,
    "PRECISION": 0,
    "SCALE": 0,
    "IS_NULLABLE": 0,
    "PRIMARY_KEY": 0,
    "ORDINAL_POSITION": 1
  },
  {
    "COLUMN_NM": "xdttm_ins",
    "DATE_TYPE": "datetime",
    "MAX_LENGTH": 8,
    "PRECISION": 23,
    "SCALE": 3,
    "IS_NULLABLE": 0,
    "PRIMARY_KEY": 0,
    "ORDINAL_POSITION": 2
  }, ........
</code>```

The header data will mostly be generic, but some of the stuff like date and etc. will need to be populated.

Initially my original thought were that I could do everything utilizing kafka connect, and that I could just create a schema for the way I want the data to be formatted. I am having a problem though with utilizing a different schema with the connectors and I'm not really sure if it is even possible.

Another solution I thought about was utilizing Kafka Streams, and writing code to transform the data into what is needed. I'm not to sure how easy it is do that w/ Kafka Streaming.

And finally a third solution I have seen is to utilize Apache Spark, and manipulating the data with dataframes. But this will add more overhead.

I'm honestly not to sure what route to go, or if any of these solutions are what I'm looking for. So I am open to all advice on how to solve this problem.

答:
Kafka Connect does have Simple Message Transforms (SMTs), a framework for making minor adjustments to the records produced by a source connector before they are written into Kafka, or to the records read from Kafka before they are send to sink connectors. Most SMTs are quite simple functions, but you can chain them together to slightly more complex operations. You can always implement your own Transformation with custom logic, but no matter what each transform operates on a single record at a time and never should make calls out to other services. SMTs are only for basic manipulation of individual records.

However, the changes you want to make are probably a bit more complex than what is suitable through SMTs. Kafka Streams seems like it is the best solution to this problem, since it allows you to create a simple stream processor that consumes the topic(s) produced by the source connector, alters (and possibly combines) the messages accordingly, and writes them out to other topic(s). Since you're already using Avro, you can write your Streams application to use Avro generic records (see this example) or with classes auto-generated from the Avro schemas (see this example).

You also mention that you have data from multiple sources, and chances are those are going to separate topics. If you want to integrate, join, combine, or simply merge those topics into other topics, then Kafka Streams is a great way to do this.

Kafka Streams apps are also just normal Java applications, so you can deploy them using the platform of your choosing, whether that's Docker, Kubernetes, Mesos, AWS, or something else. And they don't require a running distributed platform like Apache Spark requires.

Body:
I am working on a project that pulls data from multiple db sources using kafka connect. I want to then be able to transform the data into a specified json format and then finally push that final json to an S3 bucket preferably using kafka connect to keep my overhead down.

Here is an example of what the data currently looks like coming into kafka (in avro format):

{"tableName":"TABLE1","SchemaName{"string":"dbo"},"tableID":1639117030,"columnName":{"string":"DATASET"},"ordinalPosition":{"int":1},"isNullable":{"int":1},"dataType":{"string":"varchar"},"maxLength":{"int":510},"precision":{"int":0},"scale":{"int":0},"isPrimaryKey":{"int":0},"tableSizeKB":{"long":72}}
{"tableName":"dtproperties","SchemaName":{"string":"dbo"},"tableID":1745441292,"columnName":{"string":"id"},"ordinalPosition":{"int":1},"isNullable":{"int":0},"dataType":{"string":"int"},"maxLength":{"int":4},"precision":{"int":10},"scale":{"int":0},"isPrimaryKey":{"int":1},"tableSizeKB":{"long":24}}

This looks like so when converted to JSON:

{
      "tablename" : "AS_LOOKUPS",
      "tableID": 5835333,
      "columnName": "SVALUE",
      "ordinalPosition": 6,
      "isNullable": 1,
      "dataType": "varchar",
      "maxLength": 4000,
      "precision": 0,
      "scale": 0,
      "isPrimaryKey": 0,
      "tableSize": 0,
      "sizeUnit": "GB"
},
{
      "tablename" : "AS_LOOKUPS",
      "tableID": 5835333,
      "columnName": "SORT_ORDER",
      "ordinalPosition": 7,
      "isNullable": 1,
      "dataType": "int",
      "maxLength": 4,
      "precision": 10,
      "scale": 0,
      "isPrimaryKey": 0,
      "tableSize": 0,
      "sizeUnit": "GB"
}

My goal is to get the data to look like so:

{
  "header": "Database Inventory",
  "DBName": "DB",
  "ServerName": "server@server.com",
  "SchemaName": "DBE",
  "DB Owner": "Name",
  "DB Guardian" : "Name/Group",
  "ASV" : "ASVC1AUTODWH",
  "ENVCI": "ENVC1AUTODWHORE",
  "Service Owner" : "Name/Group",
  "Business Owner" : "Name/Group",
  "Support Owner" : "Name/Group",
  "Date of Data" : "2017-06-28 12:12:55.000",
  "TABLE_METADATA": {
  "TABLE_SIZE" : "500",
  "UNIT_SIZE" : "GB",
  "TABLE_ID": 117575457,
  "TABLE_NAME": "spt_fallback_db",
  "COLUMN_METADATA": [
  {
    "COLUMN_NM": "xserver_name",
    "DATE_TYPE": "varchar",
    "MAX_LENGTH": 30,
    "PRECISION": 0,
    "SCALE": 0,
    "IS_NULLABLE": 0,
    "PRIMARY_KEY": 0,
    "ORDINAL_POSITION": 1
  },
  {
    "COLUMN_NM": "xdttm_ins",
    "DATE_TYPE": "datetime",
    "MAX_LENGTH": 8,
    "PRECISION": 23,
    "SCALE": 3,
    "IS_NULLABLE": 0,
    "PRIMARY_KEY": 0,
    "ORDINAL_POSITION": 2
  }, ........

The header data will mostly be generic, but some of the stuff like date and etc. will need to be populated.

Initially my original thought were that I could do everything utilizing kafka connect, and that I could just create a schema for the way I want the data to be formatted. I am having a problem though with utilizing a different schema with the connectors and I'm not really sure if it is even possible.

Another solution I thought about was utilizing Kafka Streams, and writing code to transform the data into what is needed. I'm not to sure how easy it is do that w/ Kafka Streaming.

And finally a third solution I have seen is to utilize Apache Spark, and manipulating the data with dataframes. But this will add more overhead.

I'm honestly not to sure what route to go, or if any of these solutions are what I'm looking for. So I am open to all advice on how to solve this problem.


问:
Grab Keys from JSON Array Without Repeating
Consider the following JSON array returned from a request sent to an Elasticsearch cluster:

```<code>[
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "vodafone UK",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo",
            "demo-country-code": "GB"
        }
    },
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "Verizon",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo1",
            "demo-country-code": "US"
        }
    }
]
</code>```

I am trying to figure out how to grab all of the unique keys from this document without repeating and without hard-coding any of the values and store them into an object of the following form:

```<code>columns = ['_type', '_source.democarrier_s', '_source.m-Ecosystem_s', '_source.demo-application', '_source.demo-country-code'];
</code>```

Could someone help me figure out how to achieve this? I've been trying to loop through the document and store the keys but I can't quite figure it out. '_type' can be hard coded into the columns object because it will always exist.

Thank you in advance for your help and time.

答:
If it's just 2 levels you could do this:

var data = [
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "vodafone UK",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo",
            "demo-country-code": "GB"
        }
    },
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "Verizon",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo1",
            "demo-country-code": "US"
        }
    }
]

var keys = [];
data.forEach(function(item) {

  for (var key in item) {
    var hasProperties = false;

    if (typeof item[key] !== 'string') {

      for (var key2 in item[key]) {
        hasProperties = true;

        var keyName = key + "." + key2;

        if (keys.indexOf(keyName) < 0)
            keys.push(keyName);
      }
    }

    if (!hasProperties && keys.indexOf(key) < 0) {
       keys.push(key);
    }
 }
});

keys.forEach(function (k) { console.log(k) });```

Body:
Consider the following JSON array returned from a request sent to an Elasticsearch cluster:

[
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "vodafone UK",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo",
            "demo-country-code": "GB"
        }
    },
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "Verizon",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo1",
            "demo-country-code": "US"
        }
    }
]

I am trying to figure out how to grab all of the unique keys from this document without repeating and without hard-coding any of the values and store them into an object of the following form:

columns = ['_type', '_source.democarrier_s', '_source.m-Ecosystem_s', '_source.demo-application', '_source.demo-country-code'];

Could someone help me figure out how to achieve this? I've been trying to loop through the document and store the keys but I can't quite figure it out. '_type' can be hard coded into the columns object because it will always exist.

Thank you in advance for your help and time.


问:
MySQL AUTO_INCREMENT does not ROLLBACK
I'm using MySQL's AUTO_INCREMENT field and InnoDB to support transactions. I noticed when I rollback the transaction, the AUTO_INCREMENT field is not rollbacked? I found out that it was designed this way but are there any workarounds to this? </p>

答:
Let me point out something very important:

You should never depend on the numeric features of autogenerated keys.

That is, other than comparing them for equality (=) or unequality (<>), you should not do anything else. No relational operators (<, >), no sorting by indexes, etc. If you need to sort by "date added", have a "date added" column.

Treat them as apples and oranges: Does it make sense to ask if an apple is the same as an orange? Yes. Does it make sense to ask if an apple is larger than an orange? No. (Actually, it does, but you get my point.)

If you stick to this rule, gaps in the continuity of autogenerated indexes will not cause problems.

OwnerDisplayName: Gian Paulo

Title: MySQL AUTO_INCREMENT does not ROLLBACK

OwnerDisplayName: DrJokepu

LastEditorDisplayName: DrJokepu


问:
Is there a way to show the errorTip (error ToolTip) to the left of the target?
I'm creating an errorTip that gets displayed when the user mouses over an image. I would like the popup to appear to the left of the image, but the only properties I can pass to create the toolTip are "errorTipRight", "errorTipAbove" and "errorTipBelow".

Any thoughts?

Sample code:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[
            import mx.controls.ToolTip;
            import mx.managers.ToolTipManager;
            [Embed(source="assets/some_image.png")]
            [Bindable]
            private var myIcon:Class;

            private var myToolTip:ToolTip;

            private function showToolTip(evt:MouseEvent, text:String):void
            {
                var pt:Point = new Point(evt.currentTarget.x, evt.currentTarget.y);
                pt = evt.currentTarget.parent.contentToGlobal(pt);

                // I WANT TO POP THE ERRORTIP UP TO THE LEFT HERE INSTEAD OF ABOVE.
                myToolTip = ToolTipManager.createToolTip(text, pt.x, pt.y, "errorTipAbove") as ToolTip;
                var yOffset:int =  myToolTip.height + 5;
                myToolTip.y -= yOffset;
            }

            // Remove the tooltip
            private function killToolTip():void
            {
                ToolTipManager.destroyToolTip(myToolTip);
            }
        ]]>
    </fx:Script>
    <mx:Image source="{myIcon}" mouseOver="showToolTip(event, 'My ToolTip Message Goes Here')" mouseOut="killToolTip()" />
</mx:HBox>
</code>```

答:
Why can't you subtract the width of the tooltip from the pt.x when you give the coordinates to the ToolTipManager?</p>

```<code>myToolTip = ToolTipManager.createToolTip(text, (pt.x - somewidth), pt.y, "errorTipAbove") as ToolTip;
</code>```

Body:
I'm creating an errorTip that gets displayed when the user mouses over an image. I would like the popup to appear to the left of the image, but the only properties I can pass to create the toolTip are "errorTipRight", "errorTipAbove" and "errorTipBelow".

Any thoughts?

Sample code:

<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[
            import mx.controls.ToolTip;
            import mx.managers.ToolTipManager;
            [Embed(source="assets/some_image.png")]
            [Bindable]
            private var myIcon:Class;

            private var myToolTip:ToolTip;

            private function showToolTip(evt:MouseEvent, text:String):void
            {
                var pt:Point = new Point(evt.currentTarget.x, evt.currentTarget.y);
                pt = evt.currentTarget.parent.contentToGlobal(pt);

                // I WANT TO POP THE ERRORTIP UP TO THE LEFT HERE INSTEAD OF ABOVE.
                myToolTip = ToolTipManager.createToolTip(text, pt.x, pt.y, "errorTipAbove") as ToolTip;
                var yOffset:int =  myToolTip.height + 5;
                myToolTip.y -= yOffset;
            }

            // Remove the tooltip
            private function killToolTip():void
            {
                ToolTipManager.destroyToolTip(myToolTip);
            }
        ]]>
    </fx:Script>
    <mx:Image source="{myIcon}" mouseOver="showToolTip(event, 'My ToolTip Message Goes Here')" mouseOut="killToolTip()" />
</mx:HBox>

Body:
Why can't you subtract the width of the tooltip from the pt.x when you give the coordinates to the ToolTipManager?

myToolTip = ToolTipManager.createToolTip(text, (pt.x - somewidth), pt.y, "errorTipAbove") as ToolTip;


问:
Which command to get vagrantfile changes on an instance
I made changes to my Vagrantfile (added config.vm.share_folder, config.vm.customize lines) and now I want them to show up on the box. Do I need to run

```<code>vagrant destroy && vagrant up
</code>```

Or is it sufficient to run

```<code>vagrant reload
</code>```

? I am unclear about whether vagrant reload will read anything from the Vagrantfile, since it seems to shutdown the VM and run the provisioner.

答:
Use:</p>

```<code>vagrant reload --provision
</code>```

Body:
I made changes to my Vagrantfile (added config.vm.share_folder, config.vm.customize lines) and now I want them to show up on the box. Do I need to run

vagrant destroy && vagrant up

Or is it sufficient to run

vagrant reload

? I am unclear about whether vagrant reload will read anything from the Vagrantfile, since it seems to shutdown the VM and run the provisioner.

Body:
Use:

vagrant reload --provision