问:
Android Studio shows errors in layout.xml
I'm using data binding library and I experience following issues in Android Studio 3.0:

somelayout.xml:

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="meeting"
            type="some.package.MeetingStatusResponse"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{meeting.title}"
            tools:text="Title"
            />

            ...

    </LinearLayout>
</layout>
</code>```

In this place: android:text="@{meeting.title}" Android Studio 3.0 underlines the @ symbol and informs about error:

```<code>Error:(29, 27) <expr> or <lambda expression> expected, got '@'
</code>```

Model class is written in Kotlin if it has any relevance.
The code completion is also not working for bound classes. The application can be successfully build using both, gradle command and Android Studio run app button. So this is just editor issue.

I observe this issue on Mac. On Windows it works ok. I do not have more computers to check if it's platform related issue.

答:
Maybe you forgot to add in gradle compileOptions ?

```<code>    `sourceCompatibility JavaVersion.VERSION_1_7`
    `targetCompatibility JavaVersion.VERSION_1_7`
</code>```

Body:
I'm using data binding library and I experience following issues in Android Studio 3.0:

somelayout.xml:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="meeting"
            type="some.package.MeetingStatusResponse"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{meeting.title}"
            tools:text="Title"
            />

            ...

    </LinearLayout>
</layout>

In this place: android:text="@{meeting.title}" Android Studio 3.0 underlines the @ symbol and informs about error:

Error:(29, 27) <expr> or <lambda expression> expected, got '@'

Model class is written in Kotlin if it has any relevance.
The code completion is also not working for bound classes. The application can be successfully build using both, gradle command and Android Studio run app button. So this is just editor issue.

I observe this issue on Mac. On Windows it works ok. I do not have more computers to check if it's platform related issue.

Body:
Maybe you forgot to add in gradle compileOptions ?

    `sourceCompatibility JavaVersion.VERSION_1_7`
    `targetCompatibility JavaVersion.VERSION_1_7`


来源: stackexchange

问:
How to import nativescript pro ui modules to individual nativescript angular components without modules?
My problem is I need to import individual pro ui modules to components like lazy loading modules. However component generated by nativescript-cli doesn't have component.module.ts file. </p>

<p>Also note that global import of pro-ui modules are not working. </p>

答:
For the best practice of how to import and use the {N} Pro UI modules in {N} + Angular application, I suggest you to take a look at the sdkAngular repository here which is constantly being updated by the NativeScript team. That repository is using lazy loading for each component and app example.

On to your immediately question, if the nativescript-cli is not generating those for you maybe you want to use a different approach than the generic CLI is generating. Have you tried to manually create each component's module, the way you would do if you were developing a web Angular app? If you do that you can simply import each separate module from the {N} Pro UI like shown here.

ContentLicense: CC BY-SA 3.0

Body:
My problem is I need to import individual pro ui modules to components like lazy loading modules. However component generated by nativescript-cli doesn't have component.module.ts file.

Also note that global import of pro-ui modules are not working.


问:
Web.config transformation - How remove section on dev enviroment
I have a config section on my web.config file for URL rewrite, like this

```<code><system.webServer>
<rewrite>
  <rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
    </rule>
  </rules>
</rewrite>
</system.webServer>
</code>```

How do I use Web.config transformation to remove this section during debug?

Thanks

答:
Try</p>

```<code><system.webServer>
    <rewrite xdt:Transform="Replace"/>
</system.webServer>
</code>```

Body:
I have a config section on my web.config file for URL rewrite, like this

<system.webServer>
<rewrite>
  <rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
    </rule>
  </rules>
</rewrite>
</system.webServer>

How do I use Web.config transformation to remove this section during debug?

Thanks

Body:
Try

<system.webServer>
    <rewrite xdt:Transform="Replace"/>
</system.webServer>


问:
Disabling UAC programmatically - Change doesn't take effect?
I created a C# application that changes the "EnableLUA" key to 0,
the application is run with admin rights, and no errors pop up:

```<code>//Runs with admin rights
try
{
RegistryKey key =
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", true);
            key.SetValue("EnableLUA", "0");
            key.Close();
}
catch(Exception e)
{
    MessageBox.Show("Error: " + e);
}
</code>```

The registry key indeed gets changed from 1 to 0, but even after restarting the computer,
UAC is still enabled. Then when I go to Control Panel > User Account Control, the slider is turned all the way down. When pressing "Save" (and not having modified anything), UAC suddenly seems to be disabled.

Would this be a bug of some sort or just a weird kind of security? Is there any way around this?

答:
You can simply Remove the UAC prompt by writing two line of code,

```<code>string UAC_key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System";
Registry.SetValue(UAC_key, "EnableLUA", 0);`
</code>```

Body:
I created a C# application that changes the "EnableLUA" key to 0,
the application is run with admin rights, and no errors pop up:

//Runs with admin rights
try
{
RegistryKey key =
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", true);
            key.SetValue("EnableLUA", "0");
            key.Close();
}
catch(Exception e)
{
    MessageBox.Show("Error: " + e);
}

The registry key indeed gets changed from 1 to 0, but even after restarting the computer,
UAC is still enabled. Then when I go to Control Panel > User Account Control, the slider is turned all the way down. When pressing "Save" (and not having modified anything), UAC suddenly seems to be disabled.

Would this be a bug of some sort or just a weird kind of security? Is there any way around this?

Body:
You can simply Remove the UAC prompt by writing two line of code,

string UAC_key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System";
Registry.SetValue(UAC_key, "EnableLUA", 0);`


问:
How to generate more than one border radius
I am trying to make shapes with variable border radius.

Based on a modifier the shape should have a border radius of either 50 % (when Math.random() > 0.5), 20 % (when Math.random() > 0.8), and default to 0 % giving a plain square.

However, when you use the on-click function it will only give either the 20 % radius or the default shape, and not the 50 % radius.

Here is a simplified version of the key method:

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;

    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }
}
```

<p>The complete code snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var bestTime = 0;

var start = new Date().getTime();

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;
    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    document.getElementById("shape").style.backgroundColor = getRandomColor();
    document.getElementById("shape").style.width = width + "px";
    document.getElementById("shape").style.height = width + "px";
    document.getElementById("shape").style.top = top + "px";
    document.getElementById("shape").style.left = left + "px";
    document.getElementById("shape").style.display = "block";
    start = new Date().getTime();
}

function appearAfterDelay() {
    setTimeout(makeShapeAppear, Math.random() * 2000)
}

appearAfterDelay();

document.getElementById("shape").onclick = function() {
    document.getElementById("shape").style.display = "none";
    var end = new Date().getTime();
    var timeTaken = (end - start) / 1000;
    document.getElementById("timeTaken").innerHTML = timeTaken + "'s";
    if (timeTaken < bestTime || bestTime == 0) {
        bestTime = timeTaken;
        document.getElementById("best").innerHTML = bestTime + "s"
    }
    appearAfterDelay();
}</code>```

body {
    background-color: azure;
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

#shape {
    background-color: red;
    width: 200px;
    height: 200px;
    display: none;
    position: relative;
}

.bold {
    font-weight: bold;
}

#best {
    color: limegreen;
    font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
    <title>Javascript Test You Reactions</title>
</head>

<body>
    <h1>Test Your Reactions!</h1>
    <P>Click on the squares and circles as <em><ins>quickly</ins></em>as you can!</P>
    <p class="bold">Your time: <span id="timeTaken"></span></p>
    <p>Best time: <span id="best"></span></p>
    <div id="shape"></div>
</body></code>```

答:
You could use the following code for getting the shape radius</p>

```<code>var  randomNumber = Math.Random();
if (randomNumber > 0.8) {
    document.getElementById("shape").style.borderRadius = "20%";
}
else if (randomNumber > 0.5) {
    document.getElementById("shape").style.borderRadius = "50%";
} else {
    document.getElementById("shape").style.borderRadius = "0";
}
</code>```

Body:
I am trying to make shapes with variable border radius.

Based on a modifier the shape should have a border radius of either 50 % (when Math.random() > 0.5), 20 % (when Math.random() > 0.8), and default to 0 % giving a plain square.

However, when you use the on-click function it will only give either the 20 % radius or the default shape, and not the 50 % radius.

Here is a simplified version of the key method:

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;

    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }
}

The complete code snippet:

var bestTime = 0;

var start = new Date().getTime();

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;
    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    document.getElementById("shape").style.backgroundColor = getRandomColor();
    document.getElementById("shape").style.width = width + "px";
    document.getElementById("shape").style.height = width + "px";
    document.getElementById("shape").style.top = top + "px";
    document.getElementById("shape").style.left = left + "px";
    document.getElementById("shape").style.display = "block";
    start = new Date().getTime();
}

function appearAfterDelay() {
    setTimeout(makeShapeAppear, Math.random() * 2000)
}

appearAfterDelay();

document.getElementById("shape").onclick = function() {
    document.getElementById("shape").style.display = "none";
    var end = new Date().getTime();
    var timeTaken = (end - start) / 1000;
    document.getElementById("timeTaken").innerHTML = timeTaken + "'s";
    if (timeTaken < bestTime || bestTime == 0) {
        bestTime = timeTaken;
        document.getElementById("best").innerHTML = bestTime + "s"
    }
    appearAfterDelay();
}

body {
    background-color: azure;
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

#shape {
    background-color: red;
    width: 200px;
    height: 200px;
    display: none;
    position: relative;
}

.bold {
    font-weight: bold;
}

#best {
    color: limegreen;
    font-weight: bold;
}

    <title>Javascript Test You Reactions</title>

Test Your Reactions!

Click on the squares and circles as quicklyas you can!

Your time:

Best time:

Body:
You could use the following code for getting the shape radius

var  randomNumber = Math.Random();
if (randomNumber > 0.8) {
    document.getElementById("shape").style.borderRadius = "20%";
}
else if (randomNumber > 0.5) {
    document.getElementById("shape").style.borderRadius = "50%";
} else {
    document.getElementById("shape").style.borderRadius = "0";
}


问:
why this panda data frame doesn't append
I am hoping in the following code, the for loop will loop around all the csv in the folder, and the df data frame will append after reading from each csv.  However, the df here never appends, but only contain the content of the first csv.  Any thoughts?  Thanks!

We are in python 3.6 and pandas 0.21

```<code>    path = "/home/ubuntu/QA/client_" + CLIENT_ID + "_raw_data_" + year + "/_ACTUAL_*_Accrual*.xls"

    if CLIENT_ID in ('7')

    df_columns=pd.DataFrame(columns=['PropID','PROPERTY_CODE','TreeNodeID','ACCOUNT_CODE','TreeNodeName','ReportYear','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])

    OUTPUT_CSV="Client_"+CLIENT_ID+"_"+year+"_"+ACCOUNTING_TYPE+"_QA.csv"

    df_columns.to_csv(OUTPUT_CSV, header=True, index=False, encoding='utf-8',na_rep="NA", mode='w')

    df = pd.DataFrame()

    for fname in glob.iglob(path):

        print (fname)

        df2 = pd.DataFrame()

        df2=pd.read_excel(fname,skiprows=4,converters={'TreeNodeCode':np.int64,'PropCode':np.str}).dropna(subset=['TreeNodeCode'],how='any') ## convert the account code in the raw data into strings. dropna drops the raw of the column 4 ,which is the IAM account code, if the column 4 is NA

        print (df2)

        df=df.append(df2)

    df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE'})

    df=df.rename(columns={'PropCode':'PROPERTY_CODE'})

    df['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

    df['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

    df_QA['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

    df_QA['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

    print ("this is df")

    print (df)

    print ("this is df_QA")

    print (df_QA)

    df_check=pd.merge(df,df_QA, how='inner',on=['PROPERTY_CODE','ACCOUNT_CODE'])

    #print (df_check)

    # tricks in this ticket: https://stackoverflow.com/questions/384192823/subtracting-multiple-columns-and-appending-results-in-pandas-dataframe

    df_check[['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']] = df_check[['Jan_x','Feb_x','Mar_x','Apr_x','May_x','Jun_x','Jul_x','Aug_x','Sep_x','Oct_x','Nov_x','Dec_x']] - df_check[['Jan_y','Feb_y','Mar_y','Apr_y','May_y','Jun_y','Jul_y','Aug_y','Sep_y','Oct_y','Nov_y','Dec_y']].values

    #print (df_check)

    df_check2=df_check[['PropID','PROPERTY_CODE','TreeNodeID','ACCOUNT_CODE','TreeNodeName','ReportYear','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']]

    #print (df_check2)

    # tricks of panda query: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html#pandas-dataframe-query

    df_check3=df_check2.query('Jan > 0 | Jan < 0 | Feb > 0 | Feb < 0 | Mar > 0 | Mar < 0 | Apr > 0 | Apr < 0 | May > 0 | May < 0 | Jun > 0 | Jun < 0 | Jul > 0 | Jul < 0 | Aug > 0 | Aug < 0 | Sep > 0 | Sep < 0 | Oct > 0 | Oct < 0 | Nov > 0 | Nov < 0 | Dec > 0 | Dec < 0')

    #print (df_check3)

    #print (df_check3.info())

    df_check3.to_csv(OUTPUT_CSV, header=False, index=False,

               na_rep="NA", mode='a')
</code>```

答:
I think you need append each DataFrame to list first and then concat:

```<code>dfs = []
for fname in glob.iglob(path):
    print (fname)
    df2=pd.read_excel(fname,skiprows=4,converters={'TreeNodeCode':np.int64,'PropCode':np.str}).dropna(subset=['TreeNodeCode'],how='any') ## convert the account code in the raw data into strings. dropna drops the raw of the column 4 ,which is the IAM account code, if the column 4 is NA
    print (df2)
    dfs.append(df2)

df = pd.concat(dfs, ignore_index=True)
</code>```

Also your code:

```<code>df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE'})

df=df.rename(columns={'PropCode':'PROPERTY_CODE'})

df['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

df['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

df_QA['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

df_QA['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)
</code>```

should be simplify to:

```<code>df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE', 'PropCode':'PROPERTY_CODE'})
cols = ['PROPERTY_CODE','ACCOUNT_CODE']
df_QA[cols] = df[cols] = df_QA[cols].astype(str)
</code>```

Body:
I am hoping in the following code, the for loop will loop around all the csv in the folder, and the df data frame will append after reading from each csv.  However, the df here never appends, but only contain the content of the first csv.  Any thoughts?  Thanks!

We are in python 3.6 and pandas 0.21

    path = "/home/ubuntu/QA/client_" + CLIENT_ID + "_raw_data_" + year + "/_ACTUAL_*_Accrual*.xls"

    if CLIENT_ID in ('7')

    df_columns=pd.DataFrame(columns=['PropID','PROPERTY_CODE','TreeNodeID','ACCOUNT_CODE','TreeNodeName','ReportYear','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])

    OUTPUT_CSV="Client_"+CLIENT_ID+"_"+year+"_"+ACCOUNTING_TYPE+"_QA.csv"

    df_columns.to_csv(OUTPUT_CSV, header=True, index=False, encoding='utf-8',na_rep="NA", mode='w')

    df = pd.DataFrame()

    for fname in glob.iglob(path):

        print (fname)

        df2 = pd.DataFrame()

        df2=pd.read_excel(fname,skiprows=4,converters={'TreeNodeCode':np.int64,'PropCode':np.str}).dropna(subset=['TreeNodeCode'],how='any') ## convert the account code in the raw data into strings. dropna drops the raw of the column 4 ,which is the IAM account code, if the column 4 is NA

        print (df2)

        df=df.append(df2)

    df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE'})

    df=df.rename(columns={'PropCode':'PROPERTY_CODE'})

    df['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

    df['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

    df_QA['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

    df_QA['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

    print ("this is df")

    print (df)

    print ("this is df_QA")

    print (df_QA)

    df_check=pd.merge(df,df_QA, how='inner',on=['PROPERTY_CODE','ACCOUNT_CODE'])

    #print (df_check)

    # tricks in this ticket: https://stackoverflow.com/questions/384192823/subtracting-multiple-columns-and-appending-results-in-pandas-dataframe

    df_check[['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']] = df_check[['Jan_x','Feb_x','Mar_x','Apr_x','May_x','Jun_x','Jul_x','Aug_x','Sep_x','Oct_x','Nov_x','Dec_x']] - df_check[['Jan_y','Feb_y','Mar_y','Apr_y','May_y','Jun_y','Jul_y','Aug_y','Sep_y','Oct_y','Nov_y','Dec_y']].values

    #print (df_check)

    df_check2=df_check[['PropID','PROPERTY_CODE','TreeNodeID','ACCOUNT_CODE','TreeNodeName','ReportYear','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']]

    #print (df_check2)

    # tricks of panda query: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html#pandas-dataframe-query

    df_check3=df_check2.query('Jan > 0 | Jan < 0 | Feb > 0 | Feb < 0 | Mar > 0 | Mar < 0 | Apr > 0 | Apr < 0 | May > 0 | May < 0 | Jun > 0 | Jun < 0 | Jul > 0 | Jul < 0 | Aug > 0 | Aug < 0 | Sep > 0 | Sep < 0 | Oct > 0 | Oct < 0 | Nov > 0 | Nov < 0 | Dec > 0 | Dec < 0')

    #print (df_check3)

    #print (df_check3.info())

    df_check3.to_csv(OUTPUT_CSV, header=False, index=False,

               na_rep="NA", mode='a')

Body:
I think you need append each DataFrame to list first and then concat:

dfs = []
for fname in glob.iglob(path):
    print (fname)
    df2=pd.read_excel(fname,skiprows=4,converters={'TreeNodeCode':np.int64,'PropCode':np.str}).dropna(subset=['TreeNodeCode'],how='any') ## convert the account code in the raw data into strings. dropna drops the raw of the column 4 ,which is the IAM account code, if the column 4 is NA
    print (df2)
    dfs.append(df2)

df = pd.concat(dfs, ignore_index=True)

Also your code:

df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE'})

df=df.rename(columns={'PropCode':'PROPERTY_CODE'})

df['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

df['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

df_QA['PROPERTY_CODE'] = df_QA['PROPERTY_CODE'].astype(np.str)

df_QA['ACCOUNT_CODE'] = df_QA['ACCOUNT_CODE'].astype(np.str)

should be simplify to:

df=df.rename(columns={'TreeNodeCode':'ACCOUNT_CODE', 'PropCode':'PROPERTY_CODE'})
cols = ['PROPERTY_CODE','ACCOUNT_CODE']
df_QA[cols] = df[cols] = df_QA[cols].astype(str)


问:
Not able to see the data in componentWillMount()?
I am doing the .get() request in Jquery and updated the state as well.

My question is:

Why am I not able to see the data in console.log(this.state.storage) in componentWillMount() as well as componentDidMount() but I do get the output in render()?

Also I will need to do operations on fetched data, in which lifecycle I should do it?

constructor() {
  super();
  this.state = {
    storage: []
  }
}

componentWillMount() {
  $.get('data.csv', (data) => this.setState({
    storage: data
  }));
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return (

{this.state.storage}
 //Do get the Output
    );```

答:
this.setState is asynchronous in how it updates the component state; documentation here. If you want to see the changes effected by this.setState then you have to pass a callback to the function call

Also, you can do your operations in the callback of the $.get method as shown below

constructor() {
  super();
  this.state = {
    storage: []
  }
}

myCustomOperations = (data) => {
  // do custom operations here with data
}

componentWillMount() {
  $.get('data.csv', (data) => {
    this.myCustomOperation(data);
    this.setState({
      storage: data
    }, () => {
      console.log(this.state.storage); // correct output
      // this.myCustomOperation(this.state.storage) // if you want to do the custom operation after the data has been put into the state
    });
  });
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return (

{this.state.storage}
 //Do get the Output
    );```

Body:
this.setState is asynchronous in how it updates the component state; documentation here. If you want to see the changes effected by this.setState then you have to pass a callback to the function call

Also, you can do your operations in the callback of the $.get method as shown below

constructor() {
  super();
  this.state = {
    storage: []
  }
}

myCustomOperations = (data) => {
  // do custom operations here with data
}

componentWillMount() {
  $.get('data.csv', (data) => {
    this.myCustomOperation(data);
    this.setState({
      storage: data
    }, () => {
      console.log(this.state.storage); // correct output
      // this.myCustomOperation(this.state.storage) // if you want to do the custom operation after the data has been put into the state
    });
  });
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return (
    <div >{this.state.storage}</div> //Do get the Output
    );


问:
How to find shared library used by a python module?
I am debugging a python program based on pygtk and I want to make sure that the program is using the right shared library.

pygtk is a GTK+ wrapper for python. I have already compiled GTK+ using jhbuild tool and I want to make sure that the python script which I am debugging uses the compiled library from jhbuild.

One would import gtk and pygtk like this:

```<code>import gtk
import pygtk
print(gtk.__file__)
# /usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.pyc
print(pygtk.__file__)
# /usr/lib/python2.7/site-packages/pygtk.pyc
</code>```

For example I can show a window using gtk:

```<code>w = gtk.Window()
w.show()
</code>```

This will draw a window on the screen using gtk. However I don't know which shared object is be used. I have many versions installed and I need to find the culprit.

答:
Whenever I want to know who uses what, strace is my best friend.
So strace -ff -olog -eopen python yourscript.py gives you the list of all the files opened in this process and its children. It stores the files in log.* files, the extension being the pid of the process. Then you just grep -i gtk  log.* | grep py and look at the results.

However, I wonder why you're using pygtk (outdated and deprecated, last release in 2011) that only works with GTK+ 2. That's useful only if you're debugging a very old program with a very old jhbuild moduleset that still uses GTK+ 2.

If you can, you should strive to use pygobject and GTK+ 3.

https://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html

Body:
I am debugging a python program based on pygtk and I want to make sure that the program is using the right shared library.

pygtk is a GTK+ wrapper for python. I have already compiled GTK+ using jhbuild tool and I want to make sure that the python script which I am debugging uses the compiled library from jhbuild.

One would import gtk and pygtk like this:

import gtk
import pygtk
print(gtk.__file__)
# /usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.pyc
print(pygtk.__file__)
# /usr/lib/python2.7/site-packages/pygtk.pyc

For example I can show a window using gtk:

w = gtk.Window()
w.show()

This will draw a window on the screen using gtk. However I don't know which shared object is be used. I have many versions installed and I need to find the culprit.


问:
OrientDB spatial query throwing error: java.lang.NoSuchFieldError: INSTANCE
I am trying to evaluate OrientDB and its Spatial capabilities and cannot seem to run a simple query from browse query window

I placed orientdb-spatial-2.2.30-dist.jar in /PATH/orientdb-community-importers-2.2.29/lib/ and bounced orient db

Here is how I created the spatial index

```<code>OrientVertexType vertexType = graph.getVertexType("Foo");
ODocument location = new ODocument("OPoint");
vertexType.createProperty("location", OType.EMBEDDED, location.getSchemaClass());
ODocument metadata = new ODocument();
metadata.field("ignoreNullValues", "true");
vertexType.createIndex("Foo.location", "SPATIAL", null, metadata, "LUCENE", new String[]{"location"});
</code>```

all works without error

Here is the query I run. ( I have run several other queries too but keep getting the same stack trace...)

```<code>select from Foo where ST_DWithin(location, "POINT (-97.822 37.751)",20.0) = true
</code>```

OrientDB info:
Studio version : 2.2
OrientDB version : 2.2.29
OS: Mac

Stack trace:

```<code>java.lang.NoSuchFieldError: INSTANCE
    at com.orientechnologies.spatial.functions.OSpatialFunctionAbstractIndexable.getDb(OSpatialFunctionAbstractIndexable.java:69)
    at com.orientechnologies.spatial.functions.OSpatialFunctionAbstractIndexable.searchForIndex(OSpatialFunctionAbstractIndexable.java:57)
    at com.orientechnologies.spatial.functions.OSpatialFunctionAbstractIndexable.results(OSpatialFunctionAbstractIndexable.java:73)
    at com.orientechnologies.spatial.functions.OSTDistanceSphereFunction.estimate(OSTDistanceSphereFunction.java:82)
    at com.orientechnologies.orient.core.sql.parser.OFunctionCall.estimateIndexedFunction(OFunctionCall.java:135)
    at com.orientechnologies.orient.core.sql.parser.OLevelZeroIdentifier.estimateIndexedFunction(OLevelZeroIdentifier.java:60)
    at com.orientechnologies.orient.core.sql.parser.OBaseIdentifier.estimateIndexedFunction(OBaseIdentifier.java:57)
    at com.orientechnologies.orient.core.sql.parser.OBaseExpression.estimateIndexedFunction(OBaseExpression.java:96)
    at com.orientechnologies.orient.core.sql.parser.OExpression.estimateIndexedFunction(OExpression.java:171)
    at com.orientechnologies.orient.core.sql.parser.OBinaryCondition.estimateIndexed(OBinaryCondition.java:91)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.tryIndexedFunctions(OCommandExecutorSQLSelect.java:2318)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.searchForIndexes(OCommandExecutorSQLSelect.java:2101)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.searchInClasses(OCommandExecutorSQLSelect.java:1024)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLResultsetAbstract.assignTarget(OCommandExecutorSQLResultsetAbstract.java:211)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.assignTarget(OCommandExecutorSQLSelect.java:527)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.executeSearch(OCommandExecutorSQLSelect.java:509)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.execute(OCommandExecutorSQLSelect.java:485)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.execute(OCommandExecutorSQLDelegate.java:70)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.executeCommand(OAbstractPaginatedStorage.java:3340)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:3278)
    at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:69)
    at com.orientechnologies.orient.server.network.protocol.http.command.post.OServerCommandPostCommand.execute(OServerCommandPostCommand.java:106)
    at com.orientechnologies.orient.graph.server.command.OServerCommandPostCommandGraph.execute(OServerCommandPostCommandGraph.java:37)
    at com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpAbstract.service(ONetworkProtocolHttpAbstract.java:173)
    at com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpAbstract.execute(ONetworkProtocolHttpAbstract.java:629)
    at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:81)
$ANSI{green {db=mydb}} Exception `22001A4F` in storage `mydb`
</code>```

答:
You are using the version 2.2.30 of the plugin spatial with  2.2.29.
The version should be the same. Try to upgrade OrientDB or downgrade the Spatial plugin</p>

Body:
I am trying to evaluate OrientDB and its Spatial capabilities and cannot seem to run a simple query from browse query window

I placed orientdb-spatial-2.2.30-dist.jar in /PATH/orientdb-community-importers-2.2.29/lib/ and bounced orient db

Here is how I created the spatial index

OrientVertexType vertexType = graph.getVertexType("Foo");
ODocument location = new ODocument("OPoint");
vertexType.createProperty("location", OType.EMBEDDED, location.getSchemaClass());
ODocument metadata = new ODocument();
metadata.field("ignoreNullValues", "true");
vertexType.createIndex("Foo.location", "SPATIAL", null, metadata, "LUCENE", new String[]{"location"});

all works without error

Here is the query I run. ( I have run several other queries too but keep getting the same stack trace...)

select from Foo where ST_DWithin(location, "POINT (-97.822 37.751)",20.0) = true

OrientDB info:
Studio version : 2.2
OrientDB version : 2.2.29
OS: Mac

Stack trace:

java.lang.NoSuchFieldError: INSTANCE
    at com.orientechnologies.spatial.functions.OSpatialFunctionAbstractIndexable.getDb(OSpatialFunctionAbstractIndexable.java:69)
    at com.orientechnologies.spatial.functions.OSpatialFunctionAbstractIndexable.searchForIndex(OSpatialFunctionAbstractIndexable.java:57)
    at com.orientechnologies.spatial.functions.OSpatialFunctionAbstractIndexable.results(OSpatialFunctionAbstractIndexable.java:73)
    at com.orientechnologies.spatial.functions.OSTDistanceSphereFunction.estimate(OSTDistanceSphereFunction.java:82)
    at com.orientechnologies.orient.core.sql.parser.OFunctionCall.estimateIndexedFunction(OFunctionCall.java:135)
    at com.orientechnologies.orient.core.sql.parser.OLevelZeroIdentifier.estimateIndexedFunction(OLevelZeroIdentifier.java:60)
    at com.orientechnologies.orient.core.sql.parser.OBaseIdentifier.estimateIndexedFunction(OBaseIdentifier.java:57)
    at com.orientechnologies.orient.core.sql.parser.OBaseExpression.estimateIndexedFunction(OBaseExpression.java:96)
    at com.orientechnologies.orient.core.sql.parser.OExpression.estimateIndexedFunction(OExpression.java:171)
    at com.orientechnologies.orient.core.sql.parser.OBinaryCondition.estimateIndexed(OBinaryCondition.java:91)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.tryIndexedFunctions(OCommandExecutorSQLSelect.java:2318)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.searchForIndexes(OCommandExecutorSQLSelect.java:2101)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.searchInClasses(OCommandExecutorSQLSelect.java:1024)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLResultsetAbstract.assignTarget(OCommandExecutorSQLResultsetAbstract.java:211)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.assignTarget(OCommandExecutorSQLSelect.java:527)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.executeSearch(OCommandExecutorSQLSelect.java:509)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect.execute(OCommandExecutorSQLSelect.java:485)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.execute(OCommandExecutorSQLDelegate.java:70)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.executeCommand(OAbstractPaginatedStorage.java:3340)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:3278)
    at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:69)
    at com.orientechnologies.orient.server.network.protocol.http.command.post.OServerCommandPostCommand.execute(OServerCommandPostCommand.java:106)
    at com.orientechnologies.orient.graph.server.command.OServerCommandPostCommandGraph.execute(OServerCommandPostCommandGraph.java:37)
    at com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpAbstract.service(ONetworkProtocolHttpAbstract.java:173)
    at com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpAbstract.execute(ONetworkProtocolHttpAbstract.java:629)
    at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:81)
$ANSI{green {db=mydb}} Exception `22001A4F` in storage `mydb`


问:
Web Project vs. class library
Is there any performance difference between the two?
I have a web project that only has some classes, but not UI specific items like aspx pages or ascx controls. Should I consider to move those in a Class Library rather thank keep them as a web project ?

Thanks.

答: As far as I know there is no performance difference (or if there is it is very tiny) between a single web project, or a web project and multiple class libraries. Most large applications use the latter to compartmentalise and organise their code. In terms of execution time of each, they are both compiled so they will perform exactly the same</p>

ContentLicense: CC BY-SA 2.5

Title: Web Project vs. class library


问:
How to conform a class to a protocol in Swift and can protocol methods be overridden?
Is it necessary to use delegates to conform to a protocol? If yes, can anyone write an example code to show the same? Suppose I have a protocol ABC and I want to create a class for mocking the methods of ABC, how can this be done? I don't have very clear concepts of protocols and delegates. Please explain that too.</p>

答:
At first, protocol methods is unnecessary to conform, use @objc optional to define function:

@objc optional func webViewDidFinishLoad(webView: UIWebView)

if no @objc optional that those methods must implement in delegates.


问:
Python skipped one of my function
I am using a tkinter frame to call another tkinter frame. So from frame one i will click a button and it will check if there is a file at C:\ and if the file is not there it should call the Chrome_gui function which is another tkinter frame at "def p2(self)". When the Chrome_gui is called it will create the test file and the self.p2 will be called again to check if the file is there. But it will become a never ending loop as the function self.Chrome_guiis not called. And when i remove self.p2, the function self.Chrome_gui can be called. So can anyone tell me why it is skipping the self.Chrome_gui function?

```<code>def __init__(self):
    tk.Tk.__init__(self)
    tk.Tk.title(self,"qwerty")
    self.b1 = tk.Button(self, text="P2", command = self.p2)
    self.b1.grid(row = 3, column = 1, sticky = 'EWNS' )

def p2 (self):
            self.values()
    print ('printdwo')
    my_file1 = Path("C:\test.pdf")
    if my_file1.is_file():
        print ("File Found")
    else:
        print ('not found')
        self.Chrome_gui()
        self.p2()

def Chrome_gui(self):
    self.chrome = tk.Tk()
    self.chrome.title('Date')
    self.label = tk.Label(self.chrome, text="", width=20)
    self.label.grid(row = 1, column = 1)

    self.c1 = tk.Button(self.chrome, text="Yes", command = self.yes)
    self.c1.grid(row = 2, column = 1, sticky = W+E)#side = LEFT)
    global e
    e = ""
    self.c2 = tk.Button(self.chrome, text = "No" , command = self.no)
    self.c2.grid(row = 3, column = 1, sticky = W+E)#side = LEFT)
</code>```

答:
Your code is looping because your condition if my_file1.is_file(): is always false so it's always calling self.p2() in the else part.

When you're defining a string and you want to put a '\', you have to put '\'. In your case you have '\t' so it will replace it by a tabulation. Replace it by Path("C:\\test.pdf")

Title: Python skipped one of my function

Body:
I am using a tkinter frame to call another tkinter frame. So from frame one i will click a button and it will check if there is a file at C:\ and if the file is not there it should call the Chrome_gui function which is another tkinter frame at "def p2(self)". When the Chrome_gui is called it will create the test file and the self.p2 will be called again to check if the file is there. But it will become a never ending loop as the function self.Chrome_guiis not called. And when i remove self.p2, the function self.Chrome_gui can be called. So can anyone tell me why it is skipping the self.Chrome_gui function?

def __init__(self):
    tk.Tk.__init__(self)
    tk.Tk.title(self,"qwerty")
    self.b1 = tk.Button(self, text="P2", command = self.p2)
    self.b1.grid(row = 3, column = 1, sticky = 'EWNS' )

def p2 (self):
            self.values()
    print ('printdwo')
    my_file1 = Path("C:\test.pdf")
    if my_file1.is_file():
        print ("File Found")
    else:
        print ('not found')
        self.Chrome_gui()
        self.p2()

def Chrome_gui(self):
    self.chrome = tk.Tk()
    self.chrome.title('Date')
    self.label = tk.Label(self.chrome, text="", width=20)
    self.label.grid(row = 1, column = 1)

    self.c1 = tk.Button(self.chrome, text="Yes", command = self.yes)
    self.c1.grid(row = 2, column = 1, sticky = W+E)#side = LEFT)
    global e
    e = ""
    self.c2 = tk.Button(self.chrome, text = "No" , command = self.no)
    self.c2.grid(row = 3, column = 1, sticky = W+E)#side = LEFT)


问:
How do i write in my txt file and append text below
I cant seem to have output appears in my .txt file.
I would like to append below the text file in future.

```<code>using namespace std;

int main()
{
    string month;
    int year;
    stringstream filename;

    cin >> month;
    cin >> year;

    filename << "Expenses_" << month << "_" << year << ".txt";
    ofstream myfile(filename.str());

    myfile.open(filename.str());
    myfile << "Hello World!";
    myfile.close();

    return 0;
}
</code>```

答:
```<code>ofstream myfile(filename.str(), ofstream::out | ofstream::app);
</code>```

The constructor automatically opens the file for writing and moves the writing pointer to the end of the file, so you can append to the file. There's no need to open the file again because the std::ofstream(const char*, int) consturctor has already opened the file for you.

The alternative is:

```<code>ofstream myfile;
myfile.open(filename.str(), ofstream::out | ofstream::app);
</code>```

Body:
I cant seem to have output appears in my .txt file.
I would like to append below the text file in future.

using namespace std;

int main()
{
    string month;
    int year;
    stringstream filename;

    cin >> month;
    cin >> year;

    filename << "Expenses_" << month << "_" << year << ".txt";
    ofstream myfile(filename.str());

    myfile.open(filename.str());
    myfile << "Hello World!";
    myfile.close();

    return 0;
}

Body:
ofstream myfile(filename.str(), ofstream::out | ofstream::app);

The constructor automatically opens the file for writing and moves the writing pointer to the end of the file, so you can append to the file. There's no need to open the file again because the std::ofstream(const char*, int) consturctor has already opened the file for you.

The alternative is:

ofstream myfile;
myfile.open(filename.str(), ofstream::out | ofstream::app);


问:
How to add text file in my project so that it is not visible to user..?
Sir,

I am developing an application in which i am to save some information in text file. During execution, I wish to read/write data from/to the file(.txt file). I dont want the file to be visible to user. Or if it is visible then it must be in programfile folder of the system and user could not delete the data of the file. What should i do? I tried to add the file in Resource file but could not read and write the file. PLease help me to read/write OR provide some other way to implement the same(described above).

Thanks in advance....

答:
Put the file in the Windows System folder and use it from there.

You can access it without giving full path by using Environment.SpecialFolder.System.

This way user will have to work hard in order to find the file, but in case he does find you can't really prevent him from changing it as it's the same user running your program.


问:
Circle zero size in d3 svg angular 2 typescript
I am trying to plot a simple line graph using d3 in Angular2 typescript, Here is my code,

```<code>import { Component, ViewChild, ElementRef, Input, OnInit } from '@angular/core';
import * as d3 from 'd3';

@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><div class="chart" #chart></div>`,
})
export class AppComponent implements OnInit {
 @ViewChild('chart') private chartContainer: ElementRef;
 @Input() private data: Array<any>;
 private margin: any = { top: 20, bottom: 20, left: 20, right: 20};
 private chart: any;
 private width: number;
 private height: number;
 private xScale: any;
 private yScale: any;
 private colors: any;
 private xAxis: any;
 private yAxis: any;
 name = 'Angular';

ngOnInit() {
 this.generateData();
 this.createChart();
 if (this.data) {
     this.updateChart();
 }
}
</code>```

Here I generated random data

```<code>generateData() {
  this.data = [];
  for (let i = 0; i < (8 + Math.floor(Math.random() * 10)); i++) {
      this.data.push([
          `Index ${i}`,
          Math.floor(Math.random() * 100)
      ]);
  }
}
</code>```

Here I create X and Y axis for the line,

```<code> createChart() {

   let element = this.chartContainer.nativeElement;
   let svg = d3.select(element).append('svg');

   svg.attr('width', element.offsetWidth)
   .attr('height', element.offsetHeight);

  this.width = this.chartContainer.nativeElement.offsetWidth -
  this.margin.left - this.margin.right;
  this.height = this.chartContainer.nativeElement.offsetHeight -
  this.margin.top - this.margin.bottom;

  // chart plot area
  this.chart = svg;

  // define X & Y domains
  let xDomain = this.data.map(d => d[0]);
  let yDomain = [0, d3.max(this.data, (d: any) => {return d[1]})];

 // create scales
 this.xScale = d3.scaleBand().padding(0.1).domain(xDomain).rangeRound([0, this.width]);
 this.yScale = d3.scaleLinear().domain(yDomain).range([this.height, 0]);

// bar colors
 this.colors = d3.scaleLinear().domain([0, this.data.length]).range(<any[]>['red', 'blue']);

// x & y axis
 this.xAxis = svg.append('g')
    .attr('class', 'axis axis-x')
    .attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.height})`)
    .call(d3.axisBottom(this.xScale));
this.yAxis = svg.append('g')
    .attr('class', 'axis axis-y')
    .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
    .call(d3.axisLeft(this.yScale));
}
</code>```

Here I tried to add plots (as circle) to the places where, it has to be plotted,
everything (plot position,count) is fine, But the width and height is always zero, hence not showing up in the UI

```<code>    updateChart() {

        this.chart = this.chart.append('g')
        .attr('class', 'dots')
        .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);

        // update scales & axis
        this.xScale.domain(this.data.map(d => d[0]));
        this.yScale.domain([0, d3.max(this.data, (d:any) => {return d[1]})]);
        this.colors.domain([0, this.data.length]);
        this.xAxis.transition().call(d3.axisBottom(this.xScale));
        this.yAxis.transition().call(d3.axisLeft(this.yScale));

        let update = this.chart.selectAll('.dot')
            .data(this.data);

        update.exit().remove();

        update
            .enter()
            .append('circle')
            .attr('class', 'dot')
            .attr('cx', (d : any) => {return this.xScale(d[0])})
            .attr('cy', (d:any) =>{return this.yScale(d[1])})
            .style('fill', (d:any, i:any) => { console.log(d); return this.colors(i)});
    }
</code>```

}

As in the below image, all the plots are there, but since g is of zero height and width, they are always zero,

whereas If I replace them with 'rect' instead of 'circle' with height and width, it is showing up. I m sure some styling missing for those elements, but not sure what they are, Please give suggestions or fix

答:
You have to set the radii of the circles, otherwise it defaults to zero (actually, null):

```<code>update.enter()
    .append('circle')
    .attr('class', 'dot')
    .attr("r", someValue)//set the radius here
    .attr('cx', (d : any) => {return this.xScale(d[0])})
    .attr('cy', (d:any) =>{return this.yScale(d[1])})
    .style('fill', (d:any, i:any) => { console.log(d); return this.colors(i)});
</code>```

Body:
I am trying to plot a simple line graph using d3 in Angular2 typescript, Here is my code,

import { Component, ViewChild, ElementRef, Input, OnInit } from '@angular/core';
import * as d3 from 'd3';

@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><div class="chart" #chart></div>`,
})
export class AppComponent implements OnInit {
 @ViewChild('chart') private chartContainer: ElementRef;
 @Input() private data: Array<any>;
 private margin: any = { top: 20, bottom: 20, left: 20, right: 20};
 private chart: any;
 private width: number;
 private height: number;
 private xScale: any;
 private yScale: any;
 private colors: any;
 private xAxis: any;
 private yAxis: any;
 name = 'Angular';

ngOnInit() {
 this.generateData();
 this.createChart();
 if (this.data) {
     this.updateChart();
 }
}

Here I generated random data

generateData() {
  this.data = [];
  for (let i = 0; i < (8 + Math.floor(Math.random() * 10)); i++) {
      this.data.push([
          `Index ${i}`,
          Math.floor(Math.random() * 100)
      ]);
  }
}

Here I create X and Y axis for the line,

 createChart() {

   let element = this.chartContainer.nativeElement;
   let svg = d3.select(element).append('svg');

   svg.attr('width', element.offsetWidth)
   .attr('height', element.offsetHeight);

  this.width = this.chartContainer.nativeElement.offsetWidth -
  this.margin.left - this.margin.right;
  this.height = this.chartContainer.nativeElement.offsetHeight -
  this.margin.top - this.margin.bottom;

  // chart plot area
  this.chart = svg;

  // define X & Y domains
  let xDomain = this.data.map(d => d[0]);
  let yDomain = [0, d3.max(this.data, (d: any) => {return d[1]})];

 // create scales
 this.xScale = d3.scaleBand().padding(0.1).domain(xDomain).rangeRound([0, this.width]);
 this.yScale = d3.scaleLinear().domain(yDomain).range([this.height, 0]);

// bar colors
 this.colors = d3.scaleLinear().domain([0, this.data.length]).range(<any[]>['red', 'blue']);

// x & y axis
 this.xAxis = svg.append('g')
    .attr('class', 'axis axis-x')
    .attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.height})`)
    .call(d3.axisBottom(this.xScale));
this.yAxis = svg.append('g')
    .attr('class', 'axis axis-y')
    .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
    .call(d3.axisLeft(this.yScale));
}

Here I tried to add plots (as circle) to the places where, it has to be plotted,
everything (plot position,count) is fine, But the width and height is always zero, hence not showing up in the UI

    updateChart() {

        this.chart = this.chart.append('g')
        .attr('class', 'dots')
        .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);

        // update scales & axis
        this.xScale.domain(this.data.map(d => d[0]));
        this.yScale.domain([0, d3.max(this.data, (d:any) => {return d[1]})]);
        this.colors.domain([0, this.data.length]);
        this.xAxis.transition().call(d3.axisBottom(this.xScale));
        this.yAxis.transition().call(d3.axisLeft(this.yScale));

        let update = this.chart.selectAll('.dot')
            .data(this.data);

        update.exit().remove();

        update
            .enter()
            .append('circle')
            .attr('class', 'dot')
            .attr('cx', (d : any) => {return this.xScale(d[0])})
            .attr('cy', (d:any) =>{return this.yScale(d[1])})
            .style('fill', (d:any, i:any) => { console.log(d); return this.colors(i)});
    }

}

As in the below image, all the plots are there, but since g is of zero height and width, they are always zero,

whereas If I replace them with 'rect' instead of 'circle' with height and width, it is showing up. I m sure some styling missing for those elements, but not sure what they are, Please give suggestions or fix

Body:
You have to set the radii of the circles, otherwise it defaults to zero (actually, null):

update.enter()
    .append('circle')
    .attr('class', 'dot')
    .attr("r", someValue)//set the radius here
    .attr('cx', (d : any) => {return this.xScale(d[0])})
    .attr('cy', (d:any) =>{return this.yScale(d[1])})
    .style('fill', (d:any, i:any) => { console.log(d); return this.colors(i)});


问:
Thymeleaf form for each object in list results in "Neither BindingResult nor plain target object"
I have multiple objects inside a list and wanted to create a form for every object in that List (the user can only submit one object at once). But as soon as I use th:field instead of name and value I get an exception. Maybe someone can help me. It only happens when using the th:each; if I pass in a single object to the form it works... I reduced the problem to the minimum so its more readable :)

Exception:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'o' available as request attribute

Controller class:

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

    @GetMapping("/objectlisttest")
    public ModelAndView getObjectListTest() {
        ModelAndView mv = new ModelAndView("objectlisttest");
        List<DataObject> objects = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            DataObject o = new DataObject();
            o.setText("Dataobject");
            objects.add(o);
        }
        mv.addObject("objects", objects);
        return mv;
    }

    @PostMapping("/objectlisttest")
    public ModelAndView editObjectListTest(DataObject o, BindingResult br) {
        System.out.println(o);
        return getObjectListTest();
    }

    public static class DataObject {
        private String text;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }

}
</code>```

View:

```<code><div th:each="o : ${objects}">
    <form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
        <label>Text<input type="text" th:field="*{text}"></label>
        <input type="submit">
    </form>
</div>
</code>```

Thanks in advance

EDIT:
Changing the View to

```<code><div th:each="o : ${objects}">
    <form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
        <label>Text<input type="text" th:value="*{text}" th:name="text"></label>
        <input type="submit">
    </form>
</div>
</code>```

works. But th:field would be much nicer...

答:
It expects to have "o" object in model. If you call

```<code>mv.addObject("o", someObject);
</code>```

The error disappear I think but there would be a conflict between "o" in model and "o" as a loop variable.

I would say it's not good idea to add multiple forms with the same reference to model (all the forms has th:object="${o}").

You should redesign the logic. Either place each object separately in the model or create just one form to keep list.

Body:
I have multiple objects inside a list and wanted to create a form for every object in that List (the user can only submit one object at once). But as soon as I use th:field instead of name and value I get an exception. Maybe someone can help me. It only happens when using the th:each; if I pass in a single object to the form it works... I reduced the problem to the minimum so its more readable :)

Exception:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'o' available as request attribute

Controller class:

@Controller
public class TestController {

    @GetMapping("/objectlisttest")
    public ModelAndView getObjectListTest() {
        ModelAndView mv = new ModelAndView("objectlisttest");
        List<DataObject> objects = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            DataObject o = new DataObject();
            o.setText("Dataobject");
            objects.add(o);
        }
        mv.addObject("objects", objects);
        return mv;
    }

    @PostMapping("/objectlisttest")
    public ModelAndView editObjectListTest(DataObject o, BindingResult br) {
        System.out.println(o);
        return getObjectListTest();
    }

    public static class DataObject {
        private String text;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }

}

View:

    <form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
        Text<input type="text" th:field="*{text}">
        <input type="submit">
    </form>

Thanks in advance

EDIT:
Changing the View to

    <form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
        Text<input type="text" th:value="*{text}" th:name="text">
        <input type="submit">
    </form>

works. But th:field would be much nicer...

Body:
It expects to have "o" object in model. If you call

mv.addObject("o", someObject);

The error disappear I think but there would be a conflict between "o" in model and "o" as a loop variable.

I would say it's not good idea to add multiple forms with the same reference to model (all the forms has th:object="${o}").

You should redesign the logic. Either place each object separately in the model or create just one form to keep list.


问:
Gui freezes when using thread
I want my application to auto-refresh the content in the Vbox from the database. I have started the thread in the initialize method. Why does my Gui freezes. Is there any better way to perform such threading operation for GUI refreshing.

```<code>package Messanger.ChatWindow;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import Messanger.Login.Login;
import java.io.IOException;
import Messanger.Settings.Settings;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javax.swing.JOptionPane;

public class Controller implements Initializable {

    Settings set = new Settings();

    VBox msg_vbox = new VBox();

    @FXML
    ScrollPane scrlpane;

    @FXML
    TextField message;

    protected Model md;

    public Controller() throws SQLException {
        this.md = new Model();
    }

    @FXML
    protected void Settings() {
        try {
            set.loadView();
        } catch (IOException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    protected void Logout() throws IOException {
        Login lgin = new Login();
        lgin.loadView();
        ChatWindow.cW.close();
    }

    protected synchronized void refreshContent() throws SQLException {

        ResultSet messageArry = md.getMessages();

        while (messageArry.next()) {

            msg_vbox.getChildren().clear();

            //new label text with message.
            Label set_text = new Label();
            set_text.setText(messageArry.getString("username") + " Says: \n" + messageArry.getString("message"));
            set_text.setStyle("-fx-padding:10;"
                    + "-fx-width:100%;"
                    + "-fx-background-color:teal;"
                    + "    -fx-background-insets: 5;"
                    + "-fx-font-size:15;"
                    + "-fx-background-radius: 3;");

            set_text.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
            set_text.setWrapText(true);
            set_text.setTextAlignment(TextAlignment.JUSTIFY);
            set_text.setPrefWidth(600);

            //VBox wrapper
            msg_vbox.getChildren().addAll(set_text);
            msg_vbox.setPrefWidth(600);

            //Further wrapped by ScrollPane
            scrlpane.fitToHeightProperty();
            scrlpane.setContent(msg_vbox);
            scrlpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
            scrlpane.vvalueProperty().bind(msg_vbox.heightProperty()); //sets the scroll view to new element.
        }
    }

    @FXML
    protected void sendMessage() {
        //new label text with message.
        Label set_text = new Label();
        set_text.setText(Messanger.Login.Controller.SESSION_usrname + " Says: \n" + message.getText());
        set_text.setStyle("-fx-padding:10;"
                + "-fx-width:100%;"
                + "-fx-background-color:teal;"
                + "    -fx-background-insets: 5;"
                + "-fx-font-size:15;"
                + "-fx-background-radius: 3;");

        set_text.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
        set_text.setWrapText(true);
        set_text.setTextAlignment(TextAlignment.JUSTIFY);
        set_text.setPrefWidth(600);

        //VBox wrapper
        msg_vbox.getChildren().addAll(set_text);
        msg_vbox.setPrefWidth(600);

        //Further wrapped by ScrollPane
        scrlpane.fitToHeightProperty();
        scrlpane.setContent(msg_vbox);
        scrlpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrlpane.vvalueProperty().bind(msg_vbox.heightProperty()); //sets the scroll view to new element.
        message.setText("");
    }

    @FXML
    protected void check_key(KeyEvent ae) throws SQLException {
        if (ae.getCode().equals(KeyCode.ENTER)) {
            if (md.addMessage(Messanger.Login.Controller.SESSION_usrname, message.getText())) {
                sendMessage();
            } else {
                JOptionPane.showMessageDialog(null, "Message Sending failed \n "
                        + "Please Check Your Internet Connection", "Error ", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        scrlpane.setStyle("-fx-background:#32AED8");
        scrlpane.setPrefHeight(300);

        try {
            refreshContent();
        } catch (SQLException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

        Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                while (true) {
                                    try {
                                        refreshContent();
                                    } catch (SQLException ex) {
                                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                                    }

                                    System.out.println("asd");
                                }
                            }

                        });
                        return null;
                    }

                };
            }

        };

        service.start();
    }

}
</code>```

As in the code i've started the thread and i want to run the refreshContent method. I've also tried it implementing the Runnable interface. But same problem occurs.

答:
You are creating a new thread. However from this new thread you immediately post a Runnable to be run on the javaFX application thread that is handling the connection to the DB using a infinite loop, so you are blocking the application thread.

To not block the application thread do the long-running parts of the task on a different thread, then use Platform.runLater to update the UI.

Also you probably shouldn't initialize the rows in the result set loop...

```<code>private List<Node> refreshedContent() {
    List<Node> result = new ArrayList<>();

    ResultSet messageArry = md.getMessages();

     while (messageArry.next()) {
        // initialize nodes not yet attached to a scene
        Label set_text = new Label();
        set_text.setText(messageArry.getString("username") + " Says: \n" + messageArry.getString("message"));
        set_text.setStyle("-fx-padding:10;"
                + "-fx-width:100%;"
                + "-fx-background-color:teal;"
                + "    -fx-background-insets: 5;"
                + "-fx-font-size:15;"
                + "-fx-background-radius: 3;");

        set_text.setPrefSize(600, Region.USE_COMPUTED_SIZE);
        set_text.setWrapText(true);
        set_text.setTextAlignment(TextAlignment.JUSTIFY);

        result.add(set_text);
    }

    return result;
}

@Override
protected Void call() throws Exception {
    while (true) {
        // do long-running operation
        List<Node> newContent = refreshedContent();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                // there should be no need to do this over and over again
                // you should move it outside of the task
                msg_vbox.setPrefWidth(600);
                //scrlpane.fitToHeightProperty(); // does nothing anyway...
                scrlpane.setContent(msg_vbox);
                scrlpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
                scrlpane.vvalueProperty().bind(msg_vbox.heightProperty()); //probably won't work the intended way...

                // update ui
                msg_vbox.getChildren().setAll(newContent);
            }

        });
        // do more long-running operations
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("asd");
    }
}
</code>```

Furthermore:

Consider using ListView

Usually data access is not done from the UI layer. You could do the updates from a data access layer and make the model properties observable and update the ui on changes...

Try avoid recreating the nodes multiple times a second. ListView would help in this case. If you do not want to use a ListView you should try reusing existing Labels as much as possible instead of replacing them with new instances...

Title: Gui freezes when using thread

Body:
I want my application to auto-refresh the content in the Vbox from the database. I have started the thread in the initialize method. Why does my Gui freezes. Is there any better way to perform such threading operation for GUI refreshing.

package Messanger.ChatWindow;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import Messanger.Login.Login;
import java.io.IOException;
import Messanger.Settings.Settings;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javax.swing.JOptionPane;

public class Controller implements Initializable {

    Settings set = new Settings();

    VBox msg_vbox = new VBox();

    @FXML
    ScrollPane scrlpane;

    @FXML
    TextField message;

    protected Model md;

    public Controller() throws SQLException {
        this.md = new Model();
    }

    @FXML
    protected void Settings() {
        try {
            set.loadView();
        } catch (IOException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    protected void Logout() throws IOException {
        Login lgin = new Login();
        lgin.loadView();
        ChatWindow.cW.close();
    }

    protected synchronized void refreshContent() throws SQLException {

        ResultSet messageArry = md.getMessages();

        while (messageArry.next()) {

            msg_vbox.getChildren().clear();

            //new label text with message.
            Label set_text = new Label();
            set_text.setText(messageArry.getString("username") + " Says: \n" + messageArry.getString("message"));
            set_text.setStyle("-fx-padding:10;"
                    + "-fx-width:100%;"
                    + "-fx-background-color:teal;"
                    + "    -fx-background-insets: 5;"
                    + "-fx-font-size:15;"
                    + "-fx-background-radius: 3;");

            set_text.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
            set_text.setWrapText(true);
            set_text.setTextAlignment(TextAlignment.JUSTIFY);
            set_text.setPrefWidth(600);

            //VBox wrapper
            msg_vbox.getChildren().addAll(set_text);
            msg_vbox.setPrefWidth(600);

            //Further wrapped by ScrollPane
            scrlpane.fitToHeightProperty();
            scrlpane.setContent(msg_vbox);
            scrlpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
            scrlpane.vvalueProperty().bind(msg_vbox.heightProperty()); //sets the scroll view to new element.
        }
    }

    @FXML
    protected void sendMessage() {
        //new label text with message.
        Label set_text = new Label();
        set_text.setText(Messanger.Login.Controller.SESSION_usrname + " Says: \n" + message.getText());
        set_text.setStyle("-fx-padding:10;"
                + "-fx-width:100%;"
                + "-fx-background-color:teal;"
                + "    -fx-background-insets: 5;"
                + "-fx-font-size:15;"
                + "-fx-background-radius: 3;");

        set_text.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
        set_text.setWrapText(true);
        set_text.setTextAlignment(TextAlignment.JUSTIFY);
        set_text.setPrefWidth(600);

        //VBox wrapper
        msg_vbox.getChildren().addAll(set_text);
        msg_vbox.setPrefWidth(600);

        //Further wrapped by ScrollPane
        scrlpane.fitToHeightProperty();
        scrlpane.setContent(msg_vbox);
        scrlpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrlpane.vvalueProperty().bind(msg_vbox.heightProperty()); //sets the scroll view to new element.
        message.setText("");
    }

    @FXML
    protected void check_key(KeyEvent ae) throws SQLException {
        if (ae.getCode().equals(KeyCode.ENTER)) {
            if (md.addMessage(Messanger.Login.Controller.SESSION_usrname, message.getText())) {
                sendMessage();
            } else {
                JOptionPane.showMessageDialog(null, "Message Sending failed \n "
                        + "Please Check Your Internet Connection", "Error ", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        scrlpane.setStyle("-fx-background:#32AED8");
        scrlpane.setPrefHeight(300);

        try {
            refreshContent();
        } catch (SQLException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

        Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                while (true) {
                                    try {
                                        refreshContent();
                                    } catch (SQLException ex) {
                                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                                    }

                                    System.out.println("asd");
                                }
                            }

                        });
                        return null;
                    }

                };
            }

        };

        service.start();
    }

}

As in the code i've started the thread and i want to run the refreshContent method. I've also tried it implementing the Runnable interface. But same problem occurs.

Body:
You are creating a new thread. However from this new thread you immediately post a Runnable to be run on the javaFX application thread that is handling the connection to the DB using a infinite loop, so you are blocking the application thread.

To not block the application thread do the long-running parts of the task on a different thread, then use Platform.runLater to update the UI.

Also you probably shouldn't initialize the rows in the result set loop...

private List<Node> refreshedContent() {
    List<Node> result = new ArrayList<>();

    ResultSet messageArry = md.getMessages();

     while (messageArry.next()) {
        // initialize nodes not yet attached to a scene
        Label set_text = new Label();
        set_text.setText(messageArry.getString("username") + " Says: \n" + messageArry.getString("message"));
        set_text.setStyle("-fx-padding:10;"
                + "-fx-width:100%;"
                + "-fx-background-color:teal;"
                + "    -fx-background-insets: 5;"
                + "-fx-font-size:15;"
                + "-fx-background-radius: 3;");

        set_text.setPrefSize(600, Region.USE_COMPUTED_SIZE);
        set_text.setWrapText(true);
        set_text.setTextAlignment(TextAlignment.JUSTIFY);

        result.add(set_text);
    }

    return result;
}

@Override
protected Void call() throws Exception {
    while (true) {
        // do long-running operation
        List<Node> newContent = refreshedContent();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                // there should be no need to do this over and over again
                // you should move it outside of the task
                msg_vbox.setPrefWidth(600);
                //scrlpane.fitToHeightProperty(); // does nothing anyway...
                scrlpane.setContent(msg_vbox);
                scrlpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
                scrlpane.vvalueProperty().bind(msg_vbox.heightProperty()); //probably won't work the intended way...

                // update ui
                msg_vbox.getChildren().setAll(newContent);
            }

        });
        // do more long-running operations
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("asd");
    }
}

Furthermore:

Consider using ListView

Usually data access is not done from the UI layer. You could do the updates from a data access layer and make the model properties observable and update the ui on changes...

Try avoid recreating the nodes multiple times a second. ListView would help in this case. If you do not want to use a ListView you should try reusing existing Labels as much as possible instead of replacing them with new instances...


问:
How can I skip before action for token validations controller in Devise?
I use before action to require params in every route except auth from Devise.
So, I want to skip the before action on token validation.
I already skip in session controller and registration controller by overriding them but I don't know how to override the token validation controller.</p>

答:
Thanks for your help.
Actually, I need to override token validation controller for skip the action which runs before validating token.
Where the action is the method which I create by myself.
For the solution that I got is override TokenValidationsController for adding the skip_before_action which I already used in session controller and registration controller.

```<code>class Custom::TokenValidationsController < DeviseTokenAuth::TokenValidationsController
    skip_before_action :action, only: :validate_token
    ...
end
</code>```

Body:
Thanks for your help.
Actually, I need to override token validation controller for skip the action which runs before validating token.
Where the action is the method which I create by myself.
For the solution that I got is override TokenValidationsController for adding the skip_before_action which I already used in session controller and registration controller.

class Custom::TokenValidationsController < DeviseTokenAuth::TokenValidationsController
    skip_before_action :action, only: :validate_token
    ...
end


问:
Test string with a string list
I have a list of Id contained in an array :

```<code>var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}
</code>```

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

```<code>for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }
</code>```

I do not see how to do it .. My proposed solution does not work

答:
```<code>public listId: string[] = [];

for(let i of this.listId) {
    if(member.userId !== this.listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }
</code>```

your array not accessing outside foreach loop. you need this operator to access whole value. hope you help.

Title: Test string with a string list

Body:
I have a list of Id contained in an array :

var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

I do not see how to do it .. My proposed solution does not work

Body:
public listId: string[] = [];

for(let i of this.listId) {
    if(member.userId !== this.listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

your array not accessing outside foreach loop. you need this operator to access whole value. hope you help.


问:
SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format
I have a SQL Server table that has a "Time" column.  The table is a log table the houses status messages and timestamps for each message.  The log table is inserted into via a batch file. There is an ID column that groups rows together.  Each time the batch file runs it initializes the ID and writes records.  What I need to do is get the elapsed time from the first record in an ID set to the last record of the same ID set.  I started toying with select Max(Time) - Min(Time) from logTable where id =  but couldn't figure out how to format it correctly.  I need it in HH:MM:SS.</p>

答:
Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...

DATEDIFF(interval, date1, date2)

interval REQUIRED - The time/date part to return. Can be one of the following values:

```<code>year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
</code>```

date1, date2 REQUIRED - The two dates to calculate the difference between

Body:
Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...

DATEDIFF(interval, date1, date2)

interval REQUIRED - The time/date part to return. Can be one of the following values:

year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond

date1, date2 REQUIRED - The two dates to calculate the difference between


问:
PhpStorm not recognizing return type as extension of another
Scenario

I'm using PHP7 type hinting to say that my function has return type City.

```<code>public function getCityById(int $city_id) : City { ... }
</code>```

In this function, I return the outcome of running a finder.

```<code>return $this->city_finder->findById($city_id);
</code>```

But PhpStorm complains here, because the findById() function returns AbstractModel.

But I have class City extends AbstractModel, so this isn't a problem. PhpStorm doesn't seem to recognize this, however, and highlights the return statement with a warning.

I don't want to mute this type of warning (disable inspection), because it is an important warning to have.

Question

Can I make PhpStorm recognize that this return statement will satisfy the return type?

Additional info

One workaround is to extract a variable, and annotate it, like so:

```<code>/** @var City $city */
$city = $this->city_finder->findById($city_id);
return $city;
</code>```

At this point, it stops warning me about it, but it seems like the extra line should be avoidable since it only exists to mute a warning in the IDE.

The findById() function is protected against returning the wrong type, because a Finder class is generated on a per-model basis.

```<code>$this->city_finder = $this->orm->getFinder(City::class);
//...
$city = $city_finder->findById(...);
</code>```

答:
PHPStorm is correct.

Your findById() returns AbstractModel and it is more broad that City that you're trying to return. In a case if you'll receive from findById() some other class that is also inherited from AbstractModel, but is not a City or its descendant - you will receive fatal error from PHP and it is what PHPStorm warns you about.

You can workaround this by either adding annotation, as you do already or by explicitly checking if ($city instanceof City) {return $city; }. It may look slightly bloated by will be safe in runtime.

Body:
Scenario

I'm using PHP7 type hinting to say that my function has return type City.

public function getCityById(int $city_id) : City { ... }

In this function, I return the outcome of running a finder.

return $this->city_finder->findById($city_id);

But PhpStorm complains here, because the findById() function returns AbstractModel.

But I have class City extends AbstractModel, so this isn't a problem. PhpStorm doesn't seem to recognize this, however, and highlights the return statement with a warning.

I don't want to mute this type of warning (disable inspection), because it is an important warning to have.

Question

Can I make PhpStorm recognize that this return statement will satisfy the return type?

Additional info

One workaround is to extract a variable, and annotate it, like so:

/** @var City $city */
$city = $this->city_finder->findById($city_id);
return $city;

At this point, it stops warning me about it, but it seems like the extra line should be avoidable since it only exists to mute a warning in the IDE.

The findById() function is protected against returning the wrong type, because a Finder class is generated on a per-model basis.

$this->city_finder = $this->orm->getFinder(City::class);
//...
$city = $city_finder->findById(...);


问:
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
For example I have two dicts:

```<code>Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}
</code>```

I need a pythonic way of 'combining' two dicts such that the result is:

```<code>{'a': 1, 'b': 5, 'c': 7, 'd': 5}
</code>```

That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.

答:
Merging three dicts a,b,c in a single line without any other modules or libs

If we have the three dicts

```<code>a = {"a":9}
b = {"b":7}
c = {'b': 2, 'd': 90}
</code>```

Merge all with a single line and return a dict object using

```<code>c = dict(a.items() + b.items() + c.items())
</code>```

Returning

```<code>{'a': 9, 'b': 2, 'd': 90}
</code>```

Body:
For example I have two dicts:

Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}

I need a pythonic way of 'combining' two dicts such that the result is:

{'a': 1, 'b': 5, 'c': 7, 'd': 5}

That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.

Body:
Merging three dicts a,b,c in a single line without any other modules or libs

If we have the three dicts

a = {"a":9}
b = {"b":7}
c = {'b': 2, 'd': 90}

Merge all with a single line and return a dict object using

c = dict(a.items() + b.items() + c.items())

Returning

{'a': 9, 'b': 2, 'd': 90}


问:
Angular, TypeError: Cannot read property 'toLowerCase' of undefined
i'm trying to make a custom filter pipe by following this link, but i got error that said Angular, TypeError: Cannot read property 'toLowerCase' of undefined. I already imported the pipe to app.module.ts and also declared it in declaration. Can anyone help me with this error?

<form id="filter">
  <input type="text" class="form-control" name="term" [(ngModel)]="term" placeholder="filter by name" />
</form>

  {{product.prdName}}
  {{product.prdCat}}
  {{product.prdSup}}

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@Pipe({
  name: 'filter'
})

transform(prdName: any, term: any): any {
    if (term === undefined) return prdName;

    return prdName.filter(function(Product) {
      return Product.name.toLowerCase().includes(term.toLowerCase());
    })</code>```

答:
Is the attribute called 'name' or 'prdName' (the one you used in the template is 'prdName')?</p>

```<code>transform(values, args) {
    values.filter(
      product => product.prdName.toLowerCase().includes(args.toLowerCase())
    )
}
</code>```

Body:
i'm trying to make a custom filter pipe by following this link, but i got error that said Angular, TypeError: Cannot read property 'toLowerCase' of undefined. I already imported the pipe to app.module.ts and also declared it in declaration. Can anyone help me with this error?

<form id="filter">
  <input type="text" class="form-control" name="term" [(ngModel)]="term" placeholder="filter by name" />
</form>

  {{product.prdName}}
  {{product.prdCat}}
  {{product.prdSup}}

@Pipe({
  name: 'filter'
})

transform(prdName: any, term: any): any {
    if (term === undefined) return prdName;

    return prdName.filter(function(Product) {
      return Product.name.toLowerCase().includes(term.toLowerCase());
    })

Body:
Is the attribute called 'name' or 'prdName' (the one you used in the template is 'prdName')?

transform(values, args) {
    values.filter(
      product => product.prdName.toLowerCase().includes(args.toLowerCase())
    )
}


问:
Any references/manuals on SQL in EXCEL with Microsoft OLE DB Provider for Jet 4.0?
is there any references/manuals on SQL syntax in EXCEL connected with Microsoft OLE DB Provider for Jet 4.0 ?

For example, how do I write constants of type date?

What keywords/functions/clauses are available?

答:
When using Excel as a Jet 4.0 data source, the best reference I know of is:

How To Use ADO with Excel Data from Visual Basic or VBA.

Of particular importance is how an existing column's overall data type is determined when it contains mixed data types.

As regards the Microsoft OLE DB Provider for Jet 4.0, the most relevant article is this:

ADO Provider Properties and Settings: Microsoft Jet 4.0 Provider Properties

That said, the Excel-specific detail is better covered in the earlier article.

One important gotcha you should be aware of when using Excel and SQL:

BUG: Memory leak occurs when you query an open Excel worksheet by using ActiveX Data Objects (ADO)

What keywords/functions/clauses are
  available?

As regards using Jet 4.0 SQL, this article is the best I've ever found:

Intermediate Microsoft Jet 4.0 SQL

In theory, the SQL section of the Access Help should be relevant but it is of a particularly low quality and Jet 4.0 specifically suffers poor coverage.

Again, not everything will work directly in Excel. For example, though you can use CREATE TABLE SQL DDL to create a new worksheet and workbook, you can't create a NOT NULLable column because this isn't physically possible. Also, Excel's data types as less granular e.g. most numeric types map to DOUBLE FLOAT.

As regards expressions that can be used in SQL, the Jet 4.0 expression service somehow uses the VBA expression services. Broadly speaking, Jet can use any VBA 5.0 (not the latest version, being VBA 6.0)  function that is not a method that involes values, and returns returns a single value, of simple intrinsic data types only (no arrays, no objects, etc). I think I am correct in saying that Microsoft have never explicitly published a definitive list of the VBA functions that are supported by Jet 4.0. However, I believe a list in the following article happens to coincide perfectly with the list of VBA functions that useable in Jet 4.0:

How to configure Jet 4.0 to prevent unsafe functions from running in Access 2003

(The list is in a table under the subheading "Use Sandbox mode operations with Jet 4.0 Service Pack 3 and later".)

Note that some functions behave differently in Jet 4.0 than in VBA. Off the top of my head, I can think of two. IIF() can shortcut in Jet 4.0 (undocumented, AFAIK): in VBA, both TRUE and FALSE conditions are evaluated, in Jet 4.0 only the matched condition is evaluated. CDEC() (cast to DECIMAL) function is broken in Jet 4.0.

how do I write constants of type date?
  I mean, the way to express
  2011.01.20 (this constant value) in SQL, for example, do I use
  '2011-01-20', or #2011-01-20#, or
  something else?

I know this as a 'literal value'.

This is the same as VBA i.e. #m/d/yyyy#, so today's date would be #1/20/2011#. However, I prefer to use ISO 8601 date format and single quotes (for portability) and always include the time field (because Jet 4.0 has but one temporal data type, being DATETIME) and, to ensure regional settings are honoured, use the CDATE() cast to DATETIME function e.g. today's date would be CDATE('2011-01-20 00:00:00').

[Originally thinking the OP meant, "How do I create a column of type DATE?"]

you can use CREATE TABLE DDL e.g.

```<code>CREATE TABLE [Excel 8.0;DATABASE=C:\MyNewWorkbook.xls].MyTable
(
 my_date_col DATETIME
);
</code>```

Note that while Jet 4.0 will honour the data type of DATETIME, there is no such constraint when the workbook is edited in Excel: if the table Range is extended and non-temporal data added then the data type 'seen' by Jet 4.0 could change as a result.

Body:
When using Excel as a Jet 4.0 data source, the best reference I know of is:

How To Use ADO with Excel Data from Visual Basic or VBA.

Of particular importance is how an existing column's overall data type is determined when it contains mixed data types.

As regards the Microsoft OLE DB Provider for Jet 4.0, the most relevant article is this:

ADO Provider Properties and Settings: Microsoft Jet 4.0 Provider Properties

That said, the Excel-specific detail is better covered in the earlier article.

One important gotcha you should be aware of when using Excel and SQL:

BUG: Memory leak occurs when you query an open Excel worksheet by using ActiveX Data Objects (ADO)

What keywords/functions/clauses are
  available?

As regards using Jet 4.0 SQL, this article is the best I've ever found:

Intermediate Microsoft Jet 4.0 SQL

In theory, the SQL section of the Access Help should be relevant but it is of a particularly low quality and Jet 4.0 specifically suffers poor coverage.

Again, not everything will work directly in Excel. For example, though you can use CREATE TABLE SQL DDL to create a new worksheet and workbook, you can't create a NOT NULLable column because this isn't physically possible. Also, Excel's data types as less granular e.g. most numeric types map to DOUBLE FLOAT.

As regards expressions that can be used in SQL, the Jet 4.0 expression service somehow uses the VBA expression services. Broadly speaking, Jet can use any VBA 5.0 (not the latest version, being VBA 6.0)  function that is not a method that involes values, and returns returns a single value, of simple intrinsic data types only (no arrays, no objects, etc). I think I am correct in saying that Microsoft have never explicitly published a definitive list of the VBA functions that are supported by Jet 4.0. However, I believe a list in the following article happens to coincide perfectly with the list of VBA functions that useable in Jet 4.0:

How to configure Jet 4.0 to prevent unsafe functions from running in Access 2003

(The list is in a table under the subheading "Use Sandbox mode operations with Jet 4.0 Service Pack 3 and later".)

Note that some functions behave differently in Jet 4.0 than in VBA. Off the top of my head, I can think of two. IIF() can shortcut in Jet 4.0 (undocumented, AFAIK): in VBA, both TRUE and FALSE conditions are evaluated, in Jet 4.0 only the matched condition is evaluated. CDEC() (cast to DECIMAL) function is broken in Jet 4.0.

how do I write constants of type date?
  I mean, the way to express
  2011.01.20 (this constant value) in SQL, for example, do I use
  '2011-01-20', or #2011-01-20#, or
  something else?

I know this as a 'literal value'.

This is the same as VBA i.e. #m/d/yyyy#, so today's date would be #1/20/2011#. However, I prefer to use ISO 8601 date format and single quotes (for portability) and always include the time field (because Jet 4.0 has but one temporal data type, being DATETIME) and, to ensure regional settings are honoured, use the CDATE() cast to DATETIME function e.g. today's date would be CDATE('2011-01-20 00:00:00').

[Originally thinking the OP meant, "How do I create a column of type DATE?"]

you can use CREATE TABLE DDL e.g.

CREATE TABLE [Excel 8.0;DATABASE=C:\MyNewWorkbook.xls].MyTable
(
 my_date_col DATETIME
);

Note that while Jet 4.0 will honour the data type of DATETIME, there is no such constraint when the workbook is edited in Excel: if the table Range is extended and non-temporal data added then the data type 'seen' by Jet 4.0 could change as a result.


问:
String size in Grails too big for database field
I have Message domain class that is used to send an email to site administrators

```<code>class Message {

  String name
  String subject
  String body

}
</code>```

I thought String would not have a maximum size but when people put in messages that are too big then I see exceptions in my log files.  For now I put a constraint in to limit the size of the message to 250 but cannot make it bigger or else the save fails.  I am using PostgreSQL 9.1.1 and Grails 1.3.7.  Does anyone know a way to fix this?

答:
Setting type in constraints block doesn't work!

Put in the mapping block instead.

```<code>static mapping = {
   body type: 'text'
}
</code>```

Body:
I have Message domain class that is used to send an email to site administrators

class Message {

  String name
  String subject
  String body

}

I thought String would not have a maximum size but when people put in messages that are too big then I see exceptions in my log files.  For now I put a constraint in to limit the size of the message to 250 but cannot make it bigger or else the save fails.  I am using PostgreSQL 9.1.1 and Grails 1.3.7.  Does anyone know a way to fix this?

Body:
Setting type in constraints block doesn't work!

Put in the mapping block instead.

static mapping = {
   body type: 'text'
}

ContentLicense: CC BY-SA 4.0