问:
Reading binary values in c
I can read unsigned ints from a binary file but one of the values is printing out negative.

Expected values:

45788331,
281302247,
461354227,
13127,
299215653,
2356985123,

Values printed out:

45788331,
281302247,
461354227,
13127,
299215653,
-1932982173,

The 6th value is printing out as negative but I am reading a list of unsigned ints?

My code below

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        FILE * fp;
        ssize_t read;
        int r = 0;

        fp = fopen("numbers.bin", "rb");
        if (fp == NULL)
                exit(-1);

        while(fread(&r, sizeof(unsigned int), 1, fp) == 1)
        {
                printf("%d\n", r);
        }

        fclose(fp);
        if (line) free(line);

        exit(0);
}
</code>```

答:
Type of r is int. The range for the 32 bit int is -2147483648  = -(2^32)/2  through 2147483647 = (2^32)/2 -1 decimal.

2356985123 is outside the range for the signed int. When printing r by printf("%d\n", r);  r will be presented as -1937982173.
-1937982173 = 2356985123 - 2^32

Title: Reading binary values in c

Body:
I can read unsigned ints from a binary file but one of the values is printing out negative.

Expected values:

45788331,
281302247,
461354227,
13127,
299215653,
2356985123,

Values printed out:

45788331,
281302247,
461354227,
13127,
299215653,
-1932982173,

The 6th value is printing out as negative but I am reading a list of unsigned ints?

My code below

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        FILE * fp;
        ssize_t read;
        int r = 0;

        fp = fopen("numbers.bin", "rb");
        if (fp == NULL)
                exit(-1);

        while(fread(&r, sizeof(unsigned int), 1, fp) == 1)
        {
                printf("%d\n", r);
        }

        fclose(fp);
        if (line) free(line);

        exit(0);
}


来源: stackexchange

问:
Exception in thread "main" org.openqa.selenium.InvalidElementStateException:
Here I am opening a Chrome browser and trying to send input string to the WebElement search text box:

```<code>// search for a text in Google
WebDriverWait wait3 = new WebDriverWait(driver1,30);
WebElement textBox = wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class = 'gsfi']")));
</code>```

Error Observed for Chrome

```<code>Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.5', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir15624_26281}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=62.0.3202.94, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: d4178e5e05d8efc8800ec1e1ceb1f63a
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:100)
    at packageFF.browserAutomation.main(browserAutomation.java:76)
</code>```

答:
You're searching for input elements that have the class 'gsfi'. A quick search through the Google homepage html returns three input elements that have this class, two of them are hidden. The field that you need to send text to has an id, so why not use the id?

```<code>// The input element you need
<input class="gsfi" id="lst-ib" .../>

// Locate element by id
WebDriverWait wait = new WebDriverWait(driver1, 30);
WebElement textBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("list-ib")));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here I am opening a Chrome browser and trying to send input string to the WebElement search text box:

// search for a text in Google
WebDriverWait wait3 = new WebDriverWait(driver1,30);
WebElement textBox = wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class = 'gsfi']")));

Error Observed for Chrome

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.5', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir15624_26281}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=62.0.3202.94, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: d4178e5e05d8efc8800ec1e1ceb1f63a
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:100)
    at packageFF.browserAutomation.main(browserAutomation.java:76)

Body:
You're searching for input elements that have the class 'gsfi'. A quick search through the Google homepage html returns three input elements that have this class, two of them are hidden. The field that you need to send text to has an id, so why not use the id?

// The input element you need
<input class="gsfi" id="lst-ib" .../>

// Locate element by id
WebDriverWait wait = new WebDriverWait(driver1, 30);
WebElement textBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("list-ib")));


问:
What is Gradle in Android Studio?
Gradle is a bit confusing to me, and also for any new Android developer. Can anyone explain what Gradle in Android Studio is and what its purpose is? Why is it included in Android Studio?</p>

答:
In plain terms, Gradle is a tool provided by Android Studio in order to implement two important processes:

Build our projects

Package AndroidManifest.xml, res folder, and binary code into a specially formatted zip file called APK

ContentLicense: CC BY-SA 4.0

Title: What is Gradle in Android Studio?


问:
Applying styling to Pandas dataframe saved to HTML file
I have a Pandas dataframe inside of a Jupyter / IPython notebook. The dataframe's style as an HTML table inside of Jupyter is pretty nice. The header row has bold style, the font is nice, and the table borders are thin.

I then export the dataframe to an HTML file (following instructions here and here):

```<code>df.to_html('myfile.html')
</code>```

But the resulting HTML file's table styling is not good.

The HTML in that file is plain:

```<code><table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Id</th>
      <th>Index</th>
      <th>Feature</th>
      <th>Timestamp</th>
      <th>Feature2</th>
    </tr>
  </thead>
</code>```

How do I modify the styling of this exported table directly from my Python / Pandas code?

答:
I wrote a Python function that basically adds an HTML

    '''
    result += '
 %s
\n' % title
    if type(df) == pd.io.formats.style.Styler:
        result += df.render()
    else:
        result += df.to_html(classes='wide', escape=False)
    result += '''

'''
    with open(filename, 'w') as f:
        f.write(result)
```

<p>Here's the resulting HTML when you write it to an .html file. Note how the dataframe's <code>to_html()</code> output fits into the middle.</p>

<p><img src="https://i.stack.imgur.com/AgWJi.png" alt="enter image description here"></p>

<p>Below is some example usage of my function. I first load up a dataset from <code>sklearn</code> to demonstrate.</p>

```import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
data1 = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
                     columns=iris['feature_names'] + ['target'])
data1.head()
```

<p>In Jupyter / IPython Notebook, the table looks pretty nice:</p>

<p><img src="https://i.stack.imgur.com/3d76C.png" alt="enter image description here"></p>

<p>I can write out the dataframe to an HTML file with the usual <code>to_html()</code> function like this:</p>

```data1.to_html('iris.html')
```

<p>However, the result doesn't look good, as shown below. The border is thick and font is not pleasant because this is just a <code><table> ... </table></code> with no styling.</p>

<p><img src="https://i.stack.imgur.com/o9NUD.png" alt="enter image description here"></p>

<p><strong>To make the dataframe look better in HTML</strong>, I used my function above.</p>

```write_to_html_file(data1, 'Iris data set', 'iris2.html')
```

The table looks much nicer now because I applied styling. I also added row highlighting.

Body:
I have a Pandas dataframe inside of a Jupyter / IPython notebook. The dataframe's style as an HTML table inside of Jupyter is pretty nice. The header row has bold style, the font is nice, and the table borders are thin.

I then export the dataframe to an HTML file (following instructions here and here):

df.to_html('myfile.html')

But the resulting HTML file's table styling is not good.

The HTML in that file is plain:

      Id
      Index
      Feature
      Timestamp
      Feature2

How do I modify the styling of this exported table directly from my Python / Pandas code?

Body:
I wrote a Python function that basically adds an HTML <style> to the dataframe's HTML representation so that the resulting HTML table looks nice.

import pandas as pd

def write_to_html_file(df, title='', filename='out.html'):
    '''
    Write an entire dataframe to an HTML file with nice formatting.
    '''

    result = '''
<html>
<head>
<style>

    h2 {
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
    }
    table {
        margin-left: auto;
        margin-right: auto;
    }
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    th, td {
        padding: 5px;
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
        font-size: 90%;
    }
    table tbody tr:hover {
        background-color: #dddddd;
    }
    .wide {
        width: 90%;
    }

</style>
</head>
<body>
    '''
    result += '<h2> %s </h2>\n' % title
    if type(df) == pd.io.formats.style.Styler:
        result += df.render()
    else:
        result += df.to_html(classes='wide', escape=False)
    result += '''
</body>
</html>
'''
    with open(filename, 'w') as f:
        f.write(result)

Here's the resulting HTML when you write it to an .html file. Note how the dataframe's to_html() output fits into the middle.

Below is some example usage of my function. I first load up a dataset from sklearn to demonstrate.

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
data1 = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
                     columns=iris['feature_names'] + ['target'])
data1.head()

In Jupyter / IPython Notebook, the table looks pretty nice:

I can write out the dataframe to an HTML file with the usual to_html() function like this:

data1.to_html('iris.html')

However, the result doesn't look good, as shown below. The border is thick and font is not pleasant because this is just a <table> ... </table> with no styling.

To make the dataframe look better in HTML, I used my function above.

write_to_html_file(data1, 'Iris data set', 'iris2.html')

The table looks much nicer now because I applied styling. I also added row highlighting.


问:
Trying to take out all ATOM from pdb file
Hello I am trying to take out all the lines that start with ATOM from a pdb file. For some reason, I am having trouble. My code is:</p>

```<code>open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
my $atomcount = 0;
while ( my $lines = <FILE> ) {
    if ($lines =~ m/^ATOM.*/) {
    @newlines = $lines;
    $atomcount++;
}
}

print "@newlines\n";
print "$atomcount\n";
</code>```

答:
The line

```<code> @newlines = $lines;
</code>```

re-assigns $lines to the array @newlines and thus overwrites it with every iteration of the while loop.
You rather want to append every $lines to @newlines, so

```<code>push @newlines, $lines;
</code>```

will work.

Sidenote: The variable name $lines should be $line (just for readability) because it's just one line, not multiple lines.

Instead of explicitly counting the items appended to @newlines (with $atomcount++;) you can just use the number of items in @newlines after the loop:

```<code>my @newlines;
while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
        push @newlines, $line;
    }
}

my $atomcount = @newlines; # in scalar context this is the number of items in @newlines
print "@newlines\n";
print "$atomcount\n";
</code>```

Body:
Hello I am trying to take out all the lines that start with ATOM from a pdb file. For some reason, I am having trouble. My code is:

open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
my $atomcount = 0;
while ( my $lines = <FILE> ) {
    if ($lines =~ m/^ATOM.*/) {
    @newlines = $lines;
    $atomcount++;
}
}

print "@newlines\n";
print "$atomcount\n";

Body:
The line

 @newlines = $lines;

re-assigns $lines to the array @newlines and thus overwrites it with every iteration of the while loop.
You rather want to append every $lines to @newlines, so

push @newlines, $lines;

will work.

Sidenote: The variable name $lines should be $line (just for readability) because it's just one line, not multiple lines.

Instead of explicitly counting the items appended to @newlines (with $atomcount++;) you can just use the number of items in @newlines after the loop:

my @newlines;
while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
        push @newlines, $line;
    }
}

my $atomcount = @newlines; # in scalar context this is the number of items in @newlines
print "@newlines\n";
print "$atomcount\n";


问:
Simultaneously copying and renaming directory in ant
I've looked through ant tasks like copy, but can't really seem to find a way. With this kind of file structure:

```<code>/Resources/Docs/SpecificDoc/ScalaDocs
</code>```

I want to rename "ScalaDocs" to "TargetDocs", having an end structure like so:

```<code>/Resources/Docs/TargetDocs
</code>```

答:
Try this.</p>

```<code><copy todir="/Resources/Docs/TargetDocs">
    <fileset dir="/Resources/Docs/SpecificDoc/ScalaDocs">
        <include name="*" />
    </fileset>
</copy>
</code>```

Body:
I've looked through ant tasks like copy, but can't really seem to find a way. With this kind of file structure:

/Resources/Docs/SpecificDoc/ScalaDocs

I want to rename "ScalaDocs" to "TargetDocs", having an end structure like so:

/Resources/Docs/TargetDocs

Body:
Try this.

<copy todir="/Resources/Docs/TargetDocs">
    <fileset dir="/Resources/Docs/SpecificDoc/ScalaDocs">
        <include name="*" />
    </fileset>
</copy>


问:
How can I properly read json data from ajax response?
I did something like this:

```<code>axios.get(url).then(result => {
   this.setState({
     list: result.data,
   });
})
.catch(e => {
   console.log("Some error", e);
});
</code>```

Constructor looks like this:

```<code>constructor(props: any) {
   super(props);
   this.state = {
       list: [],
   };
}
</code>```

I want to put it somewhere and check whether it works:

```<code>const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;
</code>```

but I get uncaught TypeError: cannot read property 'list' of undefined...

It works when I do that this way:

```<code>const data: IScheduler = {
      generatedDate: "03.12.2017";
      subjects: [
          ....
      ],
};
</code>```

But it's not the point. What am I doing wrong? How should I fix it? Can somebody help me?

答:
In your state there is no property fetchedData. You set your list to this.state.list, not to this.state.fetchedData.list. So you need to change your code from:

```<code>const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;
</code>```

to:

```<code>const {list}: any = this.state;
const data: IScheduler = list;
</code>```

It should work. If you really want your first data structure you need to change your default state structure and setState, but nested data structure is not recommended.

```<code>axios.get(url).then(result => {
   this.setState({
     fetchedData: {
       list: result.data
     }
   });
})
.catch(e => {
   console.log("Some error", e);
});
</code>```

Constructor should looks like this:

```<code>constructor(props: any) {
   super(props);
   this.state = {
       fetchedData: {
         list: []
       }
   };
}
</code>```

Body:
I did something like this:

axios.get(url).then(result => {
   this.setState({
     list: result.data,
   });
})
.catch(e => {
   console.log("Some error", e);
});

Constructor looks like this:

constructor(props: any) {
   super(props);
   this.state = {
       list: [],
   };
}

I want to put it somewhere and check whether it works:

const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;

but I get uncaught TypeError: cannot read property 'list' of undefined...

It works when I do that this way:

const data: IScheduler = {
      generatedDate: "03.12.2017";
      subjects: [
          ....
      ],
};

But it's not the point. What am I doing wrong? How should I fix it? Can somebody help me?

Body:
In your state there is no property fetchedData. You set your list to this.state.list, not to this.state.fetchedData.list. So you need to change your code from:

const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;

to:

const {list}: any = this.state;
const data: IScheduler = list;

It should work. If you really want your first data structure you need to change your default state structure and setState, but nested data structure is not recommended.

axios.get(url).then(result => {
   this.setState({
     fetchedData: {
       list: result.data
     }
   });
})
.catch(e => {
   console.log("Some error", e);
});

Constructor should looks like this:

constructor(props: any) {
   super(props);
   this.state = {
       fetchedData: {
         list: []
       }
   };
}


问:
Combine pandas DataFrame query() method with isin()
So I want to use isin() method with df.query(), to select rows with id in a list: id_list. Similar question was asked before, but they used typical df[df['id'].isin(id_list)] method. I'm wondering if there is a way to use df.query() instead.

```<code>df = pd.DataFrame({'a': list('aabbccddeeff'), 'b': list('aaaabbbbcccc'),
                   'c': np.random.randint(5, size=12),
                   'd': np.random.randint(9, size=12)})

id_list = ["a", "b", "c"]
</code>```

And this yields an error

```<code>df.query('a == id_list')
</code>```

答:
You can also include the list within the query string:

```<code>>>> df.query('a in ["a", "b", "c"]')
</code>```

This is the same as:

```<code>>>> df.query('a in @id_list')
</code>```

Body:
So I want to use isin() method with df.query(), to select rows with id in a list: id_list. Similar question was asked before, but they used typical df[df['id'].isin(id_list)] method. I'm wondering if there is a way to use df.query() instead.

df = pd.DataFrame({'a': list('aabbccddeeff'), 'b': list('aaaabbbbcccc'),
                   'c': np.random.randint(5, size=12),
                   'd': np.random.randint(9, size=12)})

id_list = ["a", "b", "c"]

And this yields an error

df.query('a == id_list')

Body:
You can also include the list within the query string:

>>> df.query('a in ["a", "b", "c"]')

This is the same as:

>>> df.query('a in @id_list')


问:
Access nested dictionary items via a list of keys?
I have a complex dictionary structure which I would like to access via a list of keys to address the correct item.

dataDict = {
    "a":{
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b":{
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
        },
        "w": 3
        }
}

maplist = ["a", "r"]
```

<p>or    </p>

```maplist = ["b", "v", "y"]
```

<p>I have made the following code which works but I'm sure there is a better and more efficient way to do this if anyone has an idea.</p>

```# Get a given data from a dictionary with position provided as a list
def getFromDict(dataDict, mapList):
    for k in mapList: dataDict = dataDict[k]
    return dataDict

# Set a given data in a dictionary with position provided as a list
def setInDict(dataDict, mapList, value):
    for k in mapList[:-1]: dataDict = dataDict[k]
    dataDict[mapList[-1]] = value
```

答:
How about using recursive functions?

To get a value:

```<code>def getFromDict(dataDict, maplist):
    first, rest = maplist[0], maplist[1:]

    if rest:
        # if `rest` is not empty, run the function recursively
        return getFromDict(dataDict[first], rest)
    else:
        return dataDict[first]
</code>```

And to set a value:

```<code>def setInDict(dataDict, maplist, value):
    first, rest = maplist[0], maplist[1:]

    if rest:
        try:
            if not isinstance(dataDict[first], dict):
                # if the key is not a dict, then make it a dict
                dataDict[first] = {}
        except KeyError:
            # if key doesn't exist, create one
            dataDict[first] = {}

        setInDict(dataDict[first], rest, value)
    else:
        dataDict[first] = value
</code>```

Body:
I have a complex dictionary structure which I would like to access via a list of keys to address the correct item.

dataDict = {
    "a":{
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b":{
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
        },
        "w": 3
        }
}

maplist = ["a", "r"]

or

maplist = ["b", "v", "y"]

I have made the following code which works but I'm sure there is a better and more efficient way to do this if anyone has an idea.

# Get a given data from a dictionary with position provided as a list
def getFromDict(dataDict, mapList):
    for k in mapList: dataDict = dataDict[k]
    return dataDict

# Set a given data in a dictionary with position provided as a list
def setInDict(dataDict, mapList, value):
    for k in mapList[:-1]: dataDict = dataDict[k]
    dataDict[mapList[-1]] = value

Body:
How about using recursive functions?

To get a value:

def getFromDict(dataDict, maplist):
    first, rest = maplist[0], maplist[1:]

    if rest:
        # if `rest` is not empty, run the function recursively
        return getFromDict(dataDict[first], rest)
    else:
        return dataDict[first]

And to set a value:

def setInDict(dataDict, maplist, value):
    first, rest = maplist[0], maplist[1:]

    if rest:
        try:
            if not isinstance(dataDict[first], dict):
                # if the key is not a dict, then make it a dict
                dataDict[first] = {}
        except KeyError:
            # if key doesn't exist, create one
            dataDict[first] = {}

        setInDict(dataDict[first], rest, value)
    else:
        dataDict[first] = value


问:
How to display self pointing table?
I've a table named category. Some categories are sub-categories of other categories.

```<code>--------------------------
ID | Name | Upper_Category
--------------------------
</code>```

Upper_Category references to another category's ID.

I need to display the table like so:

```<code>ID | Name    | Upper_Category
1  | ROOT #1 | NULL
5  | exam #2 | 1
7  | exam #3 | 1
4  | ROOT #2 | NULL
9  | exam #4 | 4
2  | exam #5 | 4
3  | exam #6 | 4
6  | ROOT #3 | NULL
...
</code>```

The categories whichs Upper_Category is NULL display first and then the sub-categories which reference to them.

I tried a lot by USING JOINS and UNION but didnt succeed.

答:
If there can be more than one level of categories a recursive Common Table Expression can be used:</p>

```<code>WITH RECURSIVE r1 AS (
    SELECT * FROM t1 WHERE upper_category IS NULL
    UNION
    SELECT t1.* FROM t1, r1 WHERE r1.id = t1.upper_category)
SELECT * FROM r1;

+------+---------+----------------+
| id   | data    | upper_category |
+------+---------+----------------+
|    1 | ROOT #1 |           NULL |
|    4 | ROOT #2 |           NULL |
|    6 | ROOT #3 |           NULL |
|    5 | exam #2 |              1 |
|    7 | exam #3 |              1 |
|    9 | exam #4 |              4 |
|    2 | exam #5 |              4 |
|    3 | exam #6 |              4 |
+------+---------+----------------+
</code>```

Title: How to display self pointing table?

Body:
I've a table named category. Some categories are sub-categories of other categories.

--------------------------
ID | Name | Upper_Category
--------------------------

Upper_Category references to another category's ID.

I need to display the table like so:

ID | Name    | Upper_Category
1  | ROOT #1 | NULL
5  | exam #2 | 1
7  | exam #3 | 1
4  | ROOT #2 | NULL
9  | exam #4 | 4
2  | exam #5 | 4
3  | exam #6 | 4
6  | ROOT #3 | NULL
...

The categories whichs Upper_Category is NULL display first and then the sub-categories which reference to them.

I tried a lot by USING JOINS and UNION but didnt succeed.

Body:
If there can be more than one level of categories a recursive Common Table Expression can be used:

WITH RECURSIVE r1 AS (
    SELECT * FROM t1 WHERE upper_category IS NULL
    UNION
    SELECT t1.* FROM t1, r1 WHERE r1.id = t1.upper_category)
SELECT * FROM r1;

+------+---------+----------------+
| id   | data    | upper_category |
+------+---------+----------------+
|    1 | ROOT #1 |           NULL |
|    4 | ROOT #2 |           NULL |
|    6 | ROOT #3 |           NULL |
|    5 | exam #2 |              1 |
|    7 | exam #3 |              1 |
|    9 | exam #4 |              4 |
|    2 | exam #5 |              4 |
|    3 | exam #6 |              4 |
+------+---------+----------------+


问:
Angular 2 - Content not loading in router outlet
I'm still pretty new to Angular 2, hopefully you guys can help me out.

I have a fairly simple app, there's a login page, after successful login the user is directed to a page with a sidemenu. The login screen doesn't have this sidemenu. When the user logs out he is directed to the login page again.

The problem is that after login the sidemenu becomes visible but the other content is only visible after a refresh. Same thing for logout, after logout the page is blank, only after refresh the content (login page) is displayed. I'm probably doing something wrong but even after looking at other questions I can't figure it out.

Here's my routing:

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ProfileComponent } from './profile-component/profile-component.component'
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
import { LoggedInGuard } from './logged-in/logged-in.guard';

const appRoutes: Routes = [
  {path: 'profile', component: ProfileComponent, canActivate: [LoggedInGuard]},
  {path: 'login', component: LoginComponent},
  {path: '', component: LoginComponent},
  {path: '**', component: PageNotFoundComponent},
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {
}
</code>```

The LoginComponent:

```<code>import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {LoginService} from '../login-service/login-service.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [ LoginService ]
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  error: String;

  constructor(private formBuilder: FormBuilder,
              private loginService: LoginService,
              private router: Router) {
  }

  ngOnInit() {
    if (this.loginService.isLoggedIn()) {
      this.router.navigate(['/profile']);
    }
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  login(): void {
    let self = this;
    this.loginService.login(this.loginForm.value.username, this.loginForm.value.password).subscribe(function (result) {
      if (result) {
        self.router.navigate(['/profile']);
      }

    }, function (error) {
      self.error = 'Invalid';
    });
  }
}
</code>```

The AppComponent HTML looks like this:

```<code><md-toolbar color="primary" *ngIf="isLoggedIn()">
  <span>Sporter volgsysteem</span>
</md-toolbar>

<md-sidenav-layout *ngIf="isLoggedIn()">
  <md-sidenav #start mode="side" [opened]="true">
      <a routerLink="/add" routerLinkActive="active" md-button color="primary" disabled="false"><md-icon class="icon">add</md-icon><span class="nav-item">Toevoegen</span></a>
      <a routerLink="/compare" routerLinkActive="active" md-button color="primary"><md-icon class="icon">swap_horiz</md-icon><span class="nav-item">Vergelijken</span></a>
      <a routerLink="/search" routerLinkActive="active" md-button color="primary"><md-icon class="icon">search</md-icon><span class="nav-item">Zoeken</span></a>
      <a routerLink="/profile" routerLinkActive="active" md-button color="primary"><md-icon class="icon">account_box</md-icon><span class="nav-item">Profiel</span></a>
      <a routerLink="/feedback" routerLinkActive="active" md-button color="primary"><md-icon class="icon">feedback</md-icon><span class="nav-item">Feedback</span></a>
      <a routerLink="/faq" routerLinkActive="active" md-button color="primary"><md-icon class="icon">info</md-icon><span class="nav-item">FAQ</span></a>

      <div class="spacer"></div>

      <a md-button color="primary" routerLink="/login" (click)="logout()"><md-icon class="icon">exit_to_app</md-icon><span class="nav-item">Uitloggen</span></a>
  </md-sidenav>

  <router-outlet></router-outlet>
</md-sidenav-layout>

<router-outlet *ngIf="!isLoggedIn()"></router-outlet>
</code>```

AppComponent:

```<code>import {Component} from '@angular/core';
import {LoginService} from "./login-service/login-service.service";
import {Router } from '@angular/router'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: []
})
export class AppComponent {

  constructor(private loginService : LoginService,
              private router: Router) {
  }

  logout() {
    this.loginService.logout();
    this.router.navigate(['/login']);
  }

  isLoggedIn() {
    return this.loginService.isLoggedIn();
  }

}
</code>```

So why isn't the content of the ProfileComponent displaying after login, and why isn't the login page displaying after logout, but both display when you refresh?

Update

Most suggested that it is due to multiple unnamed router-outlets so to verify that I removed one of the outlets and show the sidemenu layout all the time. For testing purposes of course. That doesn't solve the problem, it gives me the same behaviour: the profile content is only loaded after refresh.

Update 2
I'm guessing this is related to using *ngIf to display the router-outlet

答:
Put your navigate call in a ngZone. (Angular 5)</p>

```<code>import { NgZone } from "@angular/core";
import { Router } from "@angular/router";

constructor(
    private ngZone: NgZone,
    private router: Router
) {}

...

this.ngZone.run( () => {
    this.router.navigate(['/profile']);
});
</code>```

Body:
I'm still pretty new to Angular 2, hopefully you guys can help me out.

I have a fairly simple app, there's a login page, after successful login the user is directed to a page with a sidemenu. The login screen doesn't have this sidemenu. When the user logs out he is directed to the login page again.

The problem is that after login the sidemenu becomes visible but the other content is only visible after a refresh. Same thing for logout, after logout the page is blank, only after refresh the content (login page) is displayed. I'm probably doing something wrong but even after looking at other questions I can't figure it out.

Here's my routing:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ProfileComponent } from './profile-component/profile-component.component'
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
import { LoggedInGuard } from './logged-in/logged-in.guard';

const appRoutes: Routes = [
  {path: 'profile', component: ProfileComponent, canActivate: [LoggedInGuard]},
  {path: 'login', component: LoginComponent},
  {path: '', component: LoginComponent},
  {path: '**', component: PageNotFoundComponent},
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {
}

The LoginComponent:

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {LoginService} from '../login-service/login-service.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [ LoginService ]
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  error: String;

  constructor(private formBuilder: FormBuilder,
              private loginService: LoginService,
              private router: Router) {
  }

  ngOnInit() {
    if (this.loginService.isLoggedIn()) {
      this.router.navigate(['/profile']);
    }
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  login(): void {
    let self = this;
    this.loginService.login(this.loginForm.value.username, this.loginForm.value.password).subscribe(function (result) {
      if (result) {
        self.router.navigate(['/profile']);
      }

    }, function (error) {
      self.error = 'Invalid';
    });
  }
}

The AppComponent HTML looks like this:

<md-toolbar color="primary" *ngIf="isLoggedIn()">
  Sporter volgsysteem
</md-toolbar>

<md-sidenav-layout *ngIf="isLoggedIn()">
  <md-sidenav #start mode="side" [opened]="true">
      <md-icon class="icon">add</md-icon>Toevoegen
      <md-icon class="icon">swap_horiz</md-icon>Vergelijken
      <md-icon class="icon">search</md-icon>Zoeken
      <md-icon class="icon">account_box</md-icon>Profiel
      <md-icon class="icon">feedback</md-icon>Feedback
      <md-icon class="icon">info</md-icon>FAQ

      <md-icon class="icon">exit_to_app</md-icon>Uitloggen
  </md-sidenav>

  <router-outlet></router-outlet>
</md-sidenav-layout>

<router-outlet *ngIf="!isLoggedIn()"></router-outlet>

AppComponent:

import {Component} from '@angular/core';
import {LoginService} from "./login-service/login-service.service";
import {Router } from '@angular/router'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: []
})
export class AppComponent {

  constructor(private loginService : LoginService,
              private router: Router) {
  }

  logout() {
    this.loginService.logout();
    this.router.navigate(['/login']);
  }

  isLoggedIn() {
    return this.loginService.isLoggedIn();
  }

}

So why isn't the content of the ProfileComponent displaying after login, and why isn't the login page displaying after logout, but both display when you refresh?

Update

Most suggested that it is due to multiple unnamed router-outlets so to verify that I removed one of the outlets and show the sidemenu layout all the time. For testing purposes of course. That doesn't solve the problem, it gives me the same behaviour: the profile content is only loaded after refresh.

Update 2
I'm guessing this is related to using *ngIf to display the router-outlet

Body:
Put your navigate call in a ngZone. (Angular 5)

import { NgZone } from "@angular/core";
import { Router } from "@angular/router";

constructor(
    private ngZone: NgZone,
    private router: Router
) {}

...

this.ngZone.run( () => {
    this.router.navigate(['/profile']);
});


问:
How can I open multiple files using "with open" in Python?
I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with statement:

```<code>try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror
</code>```

If that's not possible, what would an elegant solution to this problem look like?

答:
Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.

Let's say you have inFile.txt, and want to write it into two outFile's simultaneously.

```<code>with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)
</code>```

EDIT:

I don't understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile's, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.

Body:
I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with statement:

try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror

If that's not possible, what would an elegant solution to this problem look like?

Body:
Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.

Let's say you have inFile.txt, and want to write it into two outFile's simultaneously.

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

EDIT:

I don't understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile's, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.


问:
memcpy and C++ class templates - how to use it?
So.. How can we call something like
memcpy(dataCopy, data, length); to copy abstract data T?

Or if abstract T is not safe lets say we know that T is a POD (plain old data, basically a C struct) - is it possible to copy it?

答: This could be dangerous depending on the type of T. If T is a POD type, then everything's all right. Otherwise, I suggest you simply call T's copy constructor (or use a clone pattern if it's not possible).</p>

ContentLicense: CC BY-SA 2.5


问:
Matlab plot is missing corner value in plot when using comma as a decimal
To change the decimal from . to , on the x-axis and y-axis from the plot I use this function:

```<code>function decimal_comma(axis_handle, axis_name, varargin)

  switch axis_name
    case 'XY'
        decimal_comma(axis_handle, 'X', varargin{:});
        decimal_comma(axis_handle, 'Y', varargin{:});

    case {'X', 'Y'}
        tick = get(axis_handle, strcat(axis_name, 'Tick'));

        n = length(tick);
        labels = cell(1,n);

        for i = 1:n
            label = num2str(tick(i), varargin{:});
            labels{i} = strrep(label, '.', ',');
        end

        labels{1} = '';
        labels{n} = '';

        set(axis_handle, strcat(axis_name, 'TickLabel'), labels);

    otherwise
        error('Wrong axis name! Use one of X, Y or XY.');
  end
end
</code>```

my plot function :

```<code>data = load ('w3.mat');
plot(data.w3(:,1), data.w3(:,5),'g',data.w3(:,1), data.w3(:,4),'k'...
,data.w3(:,1), data.w3(:,7),'m')
hold on
x1 = data.w3(:,1);
y1 = data.w3(:,5);
y2 = data.w3(:,4);
y3 = data.w3(:,7);
err1 = 0.009*ones(size(y1));
err2 = 0.009*ones(size(y2));
err3 = 0.018*ones(size(y3));
errorbar(x1, y1, err1,'Color','green');
errorbar(x1, y2,err2,'Color','black');
errorbar(x1, y3, err3, 'Color','magenta');
lgd = legend('transmissie','reflectie','samen','Location','west','Orientation','verticol');
title(lgd,'Legenda')
title('gefolariseerd onder 0 graden ')
xlabel('hoek van inval');
ylabel('intensiteit');
decimal_comma(gca, 'X', '%.0f');
decimal_comma(gca, 'Y', '%.1f');
</code>```

When I run this function the following plot is shown

In this plot, the corner values are missing, I would like to make them visible and still have commas as a decimal in the axis.

答:
The problem is caused by the current (defaultized) xticks / yticks settings. You have to play with them in order to get corner tick marks. Alternatively, try to manipulate xlim and ylim values until you obtain a result that fit your needs.

Anyway, your method for changing the comma separators looks a bit tricky to me... I propose you the following one:

```<code>plot(x,y);
ax = gca;
ChangeDecimals(ax,'%.0f','X');
ChangeDecimals(ax,'%.1f','Y');

function ChangeDecimals(ca,fmt,opt)
    if (nargin < 1)
        ca = gca;
    end

    if (nargin < 2)
        fmt = '%.1f';
    end

    if (nargin < 3)
        opt = 'Both';
    end

    % reformat X-Axis ticks...
    if (strcmp(opt,'Both') || strcmp(opt,'X'))
        ticks = get(ca,'XTick');
        lbls = arrayfun(@(x){strrep(sprintf(fmt,x),'.',',')},ticks);
        set(ca,'XTickLabel',lbls);
    end

    % reformat Y-Axis ticks...
    if (strcmp(opt,'Both') || strcmp(opt,'Y'))
        ticks = get(ca,'YTick');
        lbls = arrayfun(@(x){strrep(sprintf(fmt,x),'.',',')},ticks);
        set(ca,'YTickLabel',lbls);
    end
end
</code>```

Body:
To change the decimal from . to , on the x-axis and y-axis from the plot I use this function:

function decimal_comma(axis_handle, axis_name, varargin)

  switch axis_name
    case 'XY'
        decimal_comma(axis_handle, 'X', varargin{:});
        decimal_comma(axis_handle, 'Y', varargin{:});

    case {'X', 'Y'}
        tick = get(axis_handle, strcat(axis_name, 'Tick'));

        n = length(tick);
        labels = cell(1,n);

        for i = 1:n
            label = num2str(tick(i), varargin{:});
            labels{i} = strrep(label, '.', ',');
        end

        labels{1} = '';
        labels{n} = '';

        set(axis_handle, strcat(axis_name, 'TickLabel'), labels);

    otherwise
        error('Wrong axis name! Use one of X, Y or XY.');
  end
end

my plot function :

data = load ('w3.mat');
plot(data.w3(:,1), data.w3(:,5),'g',data.w3(:,1), data.w3(:,4),'k'...
,data.w3(:,1), data.w3(:,7),'m')
hold on
x1 = data.w3(:,1);
y1 = data.w3(:,5);
y2 = data.w3(:,4);
y3 = data.w3(:,7);
err1 = 0.009*ones(size(y1));
err2 = 0.009*ones(size(y2));
err3 = 0.018*ones(size(y3));
errorbar(x1, y1, err1,'Color','green');
errorbar(x1, y2,err2,'Color','black');
errorbar(x1, y3, err3, 'Color','magenta');
lgd = legend('transmissie','reflectie','samen','Location','west','Orientation','verticol');
title(lgd,'Legenda')
title('gefolariseerd onder 0 graden ')
xlabel('hoek van inval');
ylabel('intensiteit');
decimal_comma(gca, 'X', '%.0f');
decimal_comma(gca, 'Y', '%.1f');

When I run this function the following plot is shown

In this plot, the corner values are missing, I would like to make them visible and still have commas as a decimal in the axis.

Body:
The problem is caused by the current (defaultized) xticks / yticks settings. You have to play with them in order to get corner tick marks. Alternatively, try to manipulate xlim and ylim values until you obtain a result that fit your needs.

Anyway, your method for changing the comma separators looks a bit tricky to me... I propose you the following one:

plot(x,y);
ax = gca;
ChangeDecimals(ax,'%.0f','X');
ChangeDecimals(ax,'%.1f','Y');

function ChangeDecimals(ca,fmt,opt)
    if (nargin < 1)
        ca = gca;
    end

    if (nargin < 2)
        fmt = '%.1f';
    end

    if (nargin < 3)
        opt = 'Both';
    end

    % reformat X-Axis ticks...
    if (strcmp(opt,'Both') || strcmp(opt,'X'))
        ticks = get(ca,'XTick');
        lbls = arrayfun(@(x){strrep(sprintf(fmt,x),'.',',')},ticks);
        set(ca,'XTickLabel',lbls);
    end

    % reformat Y-Axis ticks...
    if (strcmp(opt,'Both') || strcmp(opt,'Y'))
        ticks = get(ca,'YTick');
        lbls = arrayfun(@(x){strrep(sprintf(fmt,x),'.',',')},ticks);
        set(ca,'YTickLabel',lbls);
    end
end


问:
Why mapped list is empty?
I am new with hibernate and jpa. I need a little help. I'm developing a restful service application with spring boot. Using mysql and hibernate.

When i call my service "ingredients" array will be empty like that.
Empty array

In database ingredient table and recipe table has one to many relationship so i tried to do same thing with JPA but i can't find correct way. When I try to get Recipe i can access but ingredient list is always empty.

My Database Design:
DB Design

Recipe Entity:

```<code>import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity()
@Table(name="recipe")
@Getter
@Setter
public class Recipe {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "recipe_id")
    private int recipeId;

    @Column(name ="name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "picture_id")
    private int pictureId;

    @OneToMany(mappedBy = "recipe",fetch = FetchType.EAGER)
    private List<Ingredient> ingredients = new ArrayList<>();

}
</code>```

Ingredient Entitiy:

```<code>import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;

@Entity()
@Table(name = "ingredient")
@Getter
@Setter
public class Ingredient implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ingredient_id")
    private int ingredientId;

    @Column(name = "scale")
    private String scale;

    @ManyToOne
    @JoinColumn(name = "recipe_id",nullable = false)
    private Recipe recipe;

    @ManyToOne(cascade =  CascadeType.ALL)
    @JoinColumn(name = "material_id",nullable = false)
    private Material material;

}
</code>```

RecipeDAO:

```<code>import com.mutfak.dolapservice.dao.interfaces.IRecipeDAO;
import com.mutfak.dolapservice.entity.Recipe;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Transactional
@Repository
public class RecipeDAO implements IRecipeDAO {

    @PersistenceContext
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
    @Override
    public List<Recipe> getRecipes() {
        String query = "FROM Recipe ORDER BY recipe_id";

        return (List<Recipe>) entityManager.createQuery(query).getResultList();
    }

    @Override
    public Recipe getRecipeByMaterial(int materialId) {
        return null;
    }

    @Override
    public Recipe getRecipeById(int id) {
        return null;
    }

    @Override
    public void addRecipe(Recipe recipe) {

    }

    @Override
    public void updateRecipe(Recipe recipe) {

    }

    @Override
    public void deleteRecipe(int id) {

    }
}
</code>```

答: Finally I find solution. Lombok annotation's and JPA doesn't work correctly. JPA can't get List<> with Lombok.</p>

Title: Why mapped list is empty?

Body:
I am new with hibernate and jpa. I need a little help. I'm developing a restful service application with spring boot. Using mysql and hibernate.

When i call my service "ingredients" array will be empty like that.
Empty array

In database ingredient table and recipe table has one to many relationship so i tried to do same thing with JPA but i can't find correct way. When I try to get Recipe i can access but ingredient list is always empty.

My Database Design:
DB Design

Recipe Entity:

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity()
@Table(name="recipe")
@Getter
@Setter
public class Recipe {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "recipe_id")
    private int recipeId;

    @Column(name ="name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "picture_id")
    private int pictureId;

    @OneToMany(mappedBy = "recipe",fetch = FetchType.EAGER)
    private List<Ingredient> ingredients = new ArrayList<>();

}

Ingredient Entitiy:

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;

@Entity()
@Table(name = "ingredient")
@Getter
@Setter
public class Ingredient implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ingredient_id")
    private int ingredientId;

    @Column(name = "scale")
    private String scale;

    @ManyToOne
    @JoinColumn(name = "recipe_id",nullable = false)
    private Recipe recipe;

    @ManyToOne(cascade =  CascadeType.ALL)
    @JoinColumn(name = "material_id",nullable = false)
    private Material material;

}

RecipeDAO:

import com.mutfak.dolapservice.dao.interfaces.IRecipeDAO;
import com.mutfak.dolapservice.entity.Recipe;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Transactional
@Repository
public class RecipeDAO implements IRecipeDAO {

    @PersistenceContext
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
    @Override
    public List<Recipe> getRecipes() {
        String query = "FROM Recipe ORDER BY recipe_id";

        return (List<Recipe>) entityManager.createQuery(query).getResultList();
    }

    @Override
    public Recipe getRecipeByMaterial(int materialId) {
        return null;
    }

    @Override
    public Recipe getRecipeById(int id) {
        return null;
    }

    @Override
    public void addRecipe(Recipe recipe) {

    }

    @Override
    public void updateRecipe(Recipe recipe) {

    }

    @Override
    public void deleteRecipe(int id) {

    }
}


问:
Zoom in on a photo in canvas using javascript
I was searching for a couple of days how to solve this problem and I decided to ask here for the help.
The thing is, I made a canvas that is 640x480px and preloaded it with an image.
After I used the mouse to select the area that is going to be zoomed in (I used a draggable square, same type like if you would press mouse on windows desktop and select multiple icons) I changed the canvas to be 480x480px (since the zoom in part of the photo is a square), and within that new canvas I have displayed a new zoomed in part of that photo.

My question is: since I am doing all of this so I can zoom in on someones face so I can get a user to more precisely place dots on eyes and mouth (face recognition software like thing) how can I get real coordinates of these dots? In respect to an original image and original canvas that was 640x480px.

Everything is in pure javascript no jQuery, and without any js libraries

Thank you

答:
The same way you'd convert between Fahrenheit and Celsius: decide on a reference point and adjust your scale. The reference point is easy: (0, 0) in the zoomed context is the upper left corner of the selected area in the original context. For the scale, convert the zoomed click point from pixels to percentages. A click at (120, 240) is a click at (25%, 50%). Then multiply that percentage by the size of the selected area and add the reference point offset.</p>

```<code>// Assume the user selected in the 640x480 canvas a 223x223
// square whose upper left corner is (174, 36),
let zoomArea = {x: 174, y: 36, size: 223};

// and then clicked (120, 260) in the new 480x480 canvas.
let pointClicked = {x: 120, y: 260};

function getOriginalCoords(area, clicked) {
  const ZOOMED_SIZE = 480;

  // Get the coordinates of the clicked point in the zoomed
  // area, on a scale of 0 to 1.
  let clickedPercent = {
    x: clicked.x / ZOOMED_SIZE,
    y: clicked.y / ZOOMED_SIZE
  };

  return {
    x: clickedPercent.x * area.size + area.x,
    y: clickedPercent.y * area.size + area.y
  };
}

console.log(getOriginalCoords(zoomArea, pointClicked));
</code>```

Body:
The same way you'd convert between Fahrenheit and Celsius: decide on a reference point and adjust your scale. The reference point is easy: (0, 0) in the zoomed context is the upper left corner of the selected area in the original context. For the scale, convert the zoomed click point from pixels to percentages. A click at (120, 240) is a click at (25%, 50%). Then multiply that percentage by the size of the selected area and add the reference point offset.

// Assume the user selected in the 640x480 canvas a 223x223
// square whose upper left corner is (174, 36),
let zoomArea = {x: 174, y: 36, size: 223};

// and then clicked (120, 260) in the new 480x480 canvas.
let pointClicked = {x: 120, y: 260};

function getOriginalCoords(area, clicked) {
  const ZOOMED_SIZE = 480;

  // Get the coordinates of the clicked point in the zoomed
  // area, on a scale of 0 to 1.
  let clickedPercent = {
    x: clicked.x / ZOOMED_SIZE,
    y: clicked.y / ZOOMED_SIZE
  };

  return {
    x: clickedPercent.x * area.size + area.x,
    y: clickedPercent.y * area.size + area.y
  };
}

console.log(getOriginalCoords(zoomArea, pointClicked));


问:
How do I return a base class variable and delete it?
I'm trying to get the first element in the list and remove it.

If I return the node (ListNode*) then I won't be able to remove it. If I remove it before I return, then there will be nothing to return because it will have already been removed.

I'm trying to keep the remove capability inside the function getFirst() instead of creating a separate remove() function. By creating a temp pointer, I will still run into the same problem (not being able to delete it). I have tried to implement the deletion and ignored the get part of the requirement.

```<code>ListNode* LinkedList::getFirst(){
    ListNode *nodePtr; //traverse the list
    if(head == nullptr){
        std::cout << "List is empty no node to remove"<< std::endl;
        return nullptr;
    }
    else{
        nodePtr = head;
        head = head->next;
        delete nodePtr;
    }

    return nullptr;
}
</code>```

How can I return the pointer and delete it?

答:
Remove should not delete the object, it should only remove it from the list. You will have to delete it outside the list.

i.e.:

```<code>Node * list::get_head()
{
 if(!head)
return nullptr;
else
{
Node * ptr = head;
head = head->next;
ptr->next=mullptr;
return ptr;
}
}
</code>```

and then:

```<code>list l;
Node * ptr = l.getFirst();
...
delete ptr
</code>```

And note this is the sort of thing that are greatly improved by templates, you could make your node store data, take a copy of the data, delete the actual node and finally return the copied data.

Body:
I'm trying to get the first element in the list and remove it.

If I return the node (ListNode*) then I won't be able to remove it. If I remove it before I return, then there will be nothing to return because it will have already been removed.

I'm trying to keep the remove capability inside the function getFirst() instead of creating a separate remove() function. By creating a temp pointer, I will still run into the same problem (not being able to delete it). I have tried to implement the deletion and ignored the get part of the requirement.

ListNode* LinkedList::getFirst(){
    ListNode *nodePtr; //traverse the list
    if(head == nullptr){
        std::cout << "List is empty no node to remove"<< std::endl;
        return nullptr;
    }
    else{
        nodePtr = head;
        head = head->next;
        delete nodePtr;
    }

    return nullptr;
}

How can I return the pointer and delete it?

Body:
Remove should not delete the object, it should only remove it from the list. You will have to delete it outside the list.

i.e.:

Node * list::get_head()
{
 if(!head)
return nullptr;
else
{
Node * ptr = head;
head = head->next;
ptr->next=mullptr;
return ptr;
}
}

and then:

list l;
Node * ptr = l.getFirst();
...
delete ptr

And note this is the sort of thing that are greatly improved by templates, you could make your node store data, take a copy of the data, delete the actual node and finally return the copied data.


问:
Xamarin.forms webservice to azure database
I am a newbie in Xamarin and I am looking for a way to send information  to the azure database with Xamarin.forms, I am using webservice.

What I have done:

1-I have already created my azure database online

2-I have make the code to send information

Problem:

1-I do not know what I have to put in client.PostAsync to sending my information (email ,password, confirmpassword)

Here is the code :

```<code>public class ApiServices
    {
        public async Task <bool> RegisterAsync(string email, string password, string confirmPassword)
        {
            var client = new HttpClient();

            var model = new RegisterBindingModel
            {
                Email=email,
                Password=password,
                ConfirmPassword= confirmPassword

            };

            // to send my information
            var json = JsonConvert.SerializeObject(model);
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

              // what do I need to put in PostAsync?
            var response= await client.PostAsync("",content);

            return response.IsSuccessStatusCode;
        }
    }
</code>```

Thanks in advance .  if you have better solution and somme information to know , I will take it.

答: First argument of PostAsync must be Uri of Service, e.g. http://mywebservice.com/api/user

Body:
I am a newbie in Xamarin and I am looking for a way to send information  to the azure database with Xamarin.forms, I am using webservice.

What I have done:

1-I have already created my azure database online

2-I have make the code to send information

Problem:

1-I do not know what I have to put in client.PostAsync to sending my information (email ,password, confirmpassword)

Here is the code :

public class ApiServices
    {
        public async Task <bool> RegisterAsync(string email, string password, string confirmPassword)
        {
            var client = new HttpClient();

            var model = new RegisterBindingModel
            {
                Email=email,
                Password=password,
                ConfirmPassword= confirmPassword

            };

            // to send my information
            var json = JsonConvert.SerializeObject(model);
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

              // what do I need to put in PostAsync?
            var response= await client.PostAsync("",content);

            return response.IsSuccessStatusCode;
        }
    }

Thanks in advance .  if you have better solution and somme information to know , I will take it.


问:
How to stop internal links from turning to #REF?
I have a tab (Tab A) in my workbook that has links to another tab (Tab B and Tab C) that VBA inserts with Application.GetOpenFilename. When I run the macro I get #REF! in Tab A for the formulas on that tab (the formulas reference the inserted tabs ie Tab B and Tab C). How can I prevent this from happening and to keep the formulas on Tab A intact?

Here is my code:

```<code>Sub Data_Tab()
    '
    ' Data Tab Macro
    Dim ws As Worksheet
    Dim LastCell As Range
    Dim LastCellRowNumber As Long
    Dim sourceSheet As Worksheet
    Set sourceSheet = ActiveSheet

    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("CC_DMSR").Delete
    Sheets.Add Before:=ActiveSheet
    ActiveSheet.Name = "CC_DMSR"
    Application.DisplayAlerts = True

    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Dim Sheet As Worksheet
    Dim PasteStart As Range

    Set wb1 = ActiveWorkbook
    Set PasteStart = [CC_DMSR!A1]

    Sheets("CC_DMSR").Select
    Cells.Select
    Selection.ClearContents

    MsgBox "Please select the CC DMSR File"
    FileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a Report to Parse", _
    FileFilter:="Report Files *.xlsx (*.xlsx),")

    If FileToOpen = False Then
        MsgBox "No File Specified.", vbExclamation, "ERROR"
        Exit Sub
    Else
        Set wb2 = Workbooks.Open(Filename:=FileToOpen)

        For Each Sheet In wb2.Sheets
            With Sheet.UsedRange
                .Copy PasteStart
                Set PasteStart = PasteStart.Offset(.Rows.Count)
            End With
        Next Sheet

    End If

    wb2.Close

    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("Submitted_DMSR").Delete
    Sheets.Add Before:=ActiveSheet
    ActiveSheet.Name = "Submitted_DMSR"
    Application.DisplayAlerts = True
    Set wb1 = ActiveWorkbook
    Set PasteStart = [Submitted_DMSR!A1]

    Sheets("Submitted_DMSR").Select
    Cells.Select
    Selection.ClearContents

    MsgBox "Please select the Submitted DMSR File"
    FileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a Report to Parse", _
    FileFilter:="Report Files *.xlsx (*.xlsx),")

    If FileToOpen = False Then
        MsgBox "No File Specified.", vbExclamation, "ERROR"
        Exit Sub
    Else
        Set wb2 = Workbooks.Open(Filename:=FileToOpen)

        For Each Sheet In wb2.Sheets
            With Sheet.UsedRange
                .Copy PasteStart
                Set PasteStart = PasteStart.Offset(.Rows.Count)
            End With
        Next Sheet

    End If

    wb2.Close

    ActiveWorkbook.RefreshAll

    ActiveSheet.PivotTables("PivotTable2").PivotCache.MissingItemsLimit = _
        xlMissingItemsNone
    ActiveSheet.PivotTables("PivotTable1").PivotCache.MissingItemsLimit = _
        xlMissingItemsNone
    With Sheets("Comparison").PivotTables("PivotTable1").PivotFields("TASK/TB")
        .PivotItems("(blank)").Visible = False
    End With
    With Sheets("Comparison").PivotTables("PivotTable2").PivotFields("TASK/TB")
        .PivotItems("(blank)").Visible = False
    End With

    Dim bottomrow As Long

    Sheets("Comparison").Select
    bottomrow = Cells(Rows.Count, "B").End(xlUp).Row

    Application.ScreenUpdating = False
    Range("D4:J4").AutoFill Destination:=Range("D4:J" & bottomrow), Type:=xlFillDefault

    Application.ScreenUpdating = True

    Call sourceSheet.Activate

End Sub
</code>```

答:
I'm not sure if just opening wb2 is introducing the REF errors or the insertion of the sheets.

E.g.
If you open workbook1, which has a formula which contains a reference to workbook2, and workbook2 is then opened in Protected Mode (per default settings), Excel will introduce REF errors in any cells with references to workbook2 (due to Protected mode).

If the above is your problem, then one way might be to add wb2 as trusted document or location, or Excel>File>Options>And turn off protected mode (inadvisable).

Irrespective of the above, other solution is you using:

Range.Find and loop through all cells with references to the
sheet(s)    that will be inserted

Temporarily replace the first '=' with ' =' in these cells, which should turn the formula into a string value.

You then insert the sheets you want (string values can't experience REF errors)

Then replace ' =' with '=' to convert string back to Excel formula.

You could set a range object in step 1 that could then be reused in step 2 and 3.

Body:
I have a tab (Tab A) in my workbook that has links to another tab (Tab B and Tab C) that VBA inserts with Application.GetOpenFilename. When I run the macro I get #REF! in Tab A for the formulas on that tab (the formulas reference the inserted tabs ie Tab B and Tab C). How can I prevent this from happening and to keep the formulas on Tab A intact?

Here is my code:

Sub Data_Tab()
    '
    ' Data Tab Macro
    Dim ws As Worksheet
    Dim LastCell As Range
    Dim LastCellRowNumber As Long
    Dim sourceSheet As Worksheet
    Set sourceSheet = ActiveSheet

    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("CC_DMSR").Delete
    Sheets.Add Before:=ActiveSheet
    ActiveSheet.Name = "CC_DMSR"
    Application.DisplayAlerts = True

    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Dim Sheet As Worksheet
    Dim PasteStart As Range

    Set wb1 = ActiveWorkbook
    Set PasteStart = [CC_DMSR!A1]

    Sheets("CC_DMSR").Select
    Cells.Select
    Selection.ClearContents

    MsgBox "Please select the CC DMSR File"
    FileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a Report to Parse", _
    FileFilter:="Report Files *.xlsx (*.xlsx),")

    If FileToOpen = False Then
        MsgBox "No File Specified.", vbExclamation, "ERROR"
        Exit Sub
    Else
        Set wb2 = Workbooks.Open(Filename:=FileToOpen)

        For Each Sheet In wb2.Sheets
            With Sheet.UsedRange
                .Copy PasteStart
                Set PasteStart = PasteStart.Offset(.Rows.Count)
            End With
        Next Sheet

    End If

    wb2.Close

    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("Submitted_DMSR").Delete
    Sheets.Add Before:=ActiveSheet
    ActiveSheet.Name = "Submitted_DMSR"
    Application.DisplayAlerts = True
    Set wb1 = ActiveWorkbook
    Set PasteStart = [Submitted_DMSR!A1]

    Sheets("Submitted_DMSR").Select
    Cells.Select
    Selection.ClearContents

    MsgBox "Please select the Submitted DMSR File"
    FileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a Report to Parse", _
    FileFilter:="Report Files *.xlsx (*.xlsx),")

    If FileToOpen = False Then
        MsgBox "No File Specified.", vbExclamation, "ERROR"
        Exit Sub
    Else
        Set wb2 = Workbooks.Open(Filename:=FileToOpen)

        For Each Sheet In wb2.Sheets
            With Sheet.UsedRange
                .Copy PasteStart
                Set PasteStart = PasteStart.Offset(.Rows.Count)
            End With
        Next Sheet

    End If

    wb2.Close

    ActiveWorkbook.RefreshAll

    ActiveSheet.PivotTables("PivotTable2").PivotCache.MissingItemsLimit = _
        xlMissingItemsNone
    ActiveSheet.PivotTables("PivotTable1").PivotCache.MissingItemsLimit = _
        xlMissingItemsNone
    With Sheets("Comparison").PivotTables("PivotTable1").PivotFields("TASK/TB")
        .PivotItems("(blank)").Visible = False
    End With
    With Sheets("Comparison").PivotTables("PivotTable2").PivotFields("TASK/TB")
        .PivotItems("(blank)").Visible = False
    End With

    Dim bottomrow As Long

    Sheets("Comparison").Select
    bottomrow = Cells(Rows.Count, "B").End(xlUp).Row

    Application.ScreenUpdating = False
    Range("D4:J4").AutoFill Destination:=Range("D4:J" & bottomrow), Type:=xlFillDefault

    Application.ScreenUpdating = True

    Call sourceSheet.Activate

End Sub


问:
Is there a practical way to use IronPython entirely within the VS 2k10 IDE?
I've looked through the existing threads on IronPython and IDEs without finding an answer.

If I don't need to support Python 3, is there a practical way to do IronPython development fully inside the VS 2k10 IDE like I used to with FORTRAN.net?

答: IronPython 2.7 includes VS 2010 support - it's still only a beta but if you download and install it there's an option to install VS support.  That includes a project system, intellisense, a REPL window, object browsing, etc...</p>


问:
Assigning out/ref parameters in Moq
Is it possible to assign an out/ref parameter using Moq (3.0+)?

I've looked at using Callback(), but Action<> does not support ref parameters because it's based on generics. I'd also preferably like to put a constraint (It.Is) on the input of the ref parameter, though I can do that in the callback.

I know that Rhino Mocks supports this functionality, but the project I'm working on is already using Moq.

答:
Moq version 4.8 (or later) has much improved support for by-ref parameters:

```<code>public interface IGobbler
{
    bool Gobble(ref int amount);
}

delegate void GobbleCallback(ref int amount);     // needed for Callback
delegate bool GobbleReturns(ref int amount);      // needed for Returns

var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))  // match any value passed by-ref
    .Callback(new GobbleCallback((ref int amount) =>
     {
         if (amount > 0)
         {
             Console.WriteLine("Gobbling...");
             amount -= 1;
         }
     }))
    .Returns(new GobbleReturns((ref int amount) => amount > 0));

int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
    gobbleSomeMore = mock.Object.Gobble(ref a);
}
</code>```

The same pattern works for out parameters.

It.Ref<T>.IsAny also works for C# 7 in parameters (since they are also by-ref).

Title: Assigning out/ref parameters in Moq

Body:
Moq version 4.8 (or later) has much improved support for by-ref parameters:

public interface IGobbler
{
    bool Gobble(ref int amount);
}

delegate void GobbleCallback(ref int amount);     // needed for Callback
delegate bool GobbleReturns(ref int amount);      // needed for Returns

var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))  // match any value passed by-ref
    .Callback(new GobbleCallback((ref int amount) =>
     {
         if (amount > 0)
         {
             Console.WriteLine("Gobbling...");
             amount -= 1;
         }
     }))
    .Returns(new GobbleReturns((ref int amount) => amount > 0));

int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
    gobbleSomeMore = mock.Object.Gobble(ref a);
}

The same pattern works for out parameters.

It.Ref<T>.IsAny also works for C# 7 in parameters (since they are also by-ref).


问:
NetSuite SuiteScript How to bridge the 10MG limit?
HI and thanks for any help. Is there a way to work with files larger than 10mg? I have to check for updates on items in a file that would be uploaded, but the file contains all items in the system and is approximately 20MG. This 10MG limit is killing me. I see streaming for file save and appending but not for file reading. So I am open to any suggestions. The provider in this instance doesn't offer the facility to chunk the files. thanks in advance for your help. </p>

答:
If you are using SS2 to process a file from the file cabinet then if you use file.lines.iterator() to process a file the size limit is 10MB per line.

I believe returning a file object from a map reduce script's getInputStage automatically parses the file into lines.

The 10MB file size limit comes into play if you try to create a file larger than 10MB.

If you are trying to read in a an external file via script then one approach that I've used is to proxy the call via an external service. e.g. query an AWS lambda function that checks for and saves the file to S3. Return the file path and size to your SuiteScript. The SuiteScript then asks for "pages" of the file that are less than 10MB and saves those. If you are uploading something like a .csv then the lambda function can send the header with each paged request.


问:
Excel Macro does not display properly
I have a macro that is supposed to copy the format of a row and insert a new row with the same format.

Here is the macro code:

```<code>Sub Insertion_ligne_verrouillée()
'
' Insertion_ligne_verrouillée Macro
    ActiveSheet.Unprotect
    ActiveCell.Offset(-1, 0).EntireRow.Copy
    Rows(ActiveCell.Row).Insert Shift:=xlDown
    On Error Resume Next
    Rows(ActiveCell.Row).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveSheet.Unprotect
     'Application.CutCopyMode=False
End Sub
</code>```

Now i am not the one that wrote the macro and honestly my VBA is quite rusty (also not that good in VBA either). The problem i am having is the user is using the macro by selecting a row and using ctrl+L.

It does copy and insert a row with the right format, however some rows afterward seem empty (all blank and no row number) so you have to select the row > right click > display, for it to display properly

Not sure what to look for

答:
The following code makes a new row below the row you want to copy then copies the format of the row and paste into the new row.</p>

```<code>Sub Insertion_ligne_verrouillée()
  'Make a new row below active cell
  ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown,
  CopyOrigin:=xlFormatFromRightOrAbove
  'Copy the active row
  ActiveCell.EntireRow.Copy
  'paste format into new row
  ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
  Application.CutCopyMode = False
End Sub
</code>```

Title: Excel Macro does not display properly

Body:
I have a macro that is supposed to copy the format of a row and insert a new row with the same format.

Here is the macro code:

Sub Insertion_ligne_verrouillée()
'
' Insertion_ligne_verrouillée Macro
    ActiveSheet.Unprotect
    ActiveCell.Offset(-1, 0).EntireRow.Copy
    Rows(ActiveCell.Row).Insert Shift:=xlDown
    On Error Resume Next
    Rows(ActiveCell.Row).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveSheet.Unprotect
     'Application.CutCopyMode=False
End Sub

Now i am not the one that wrote the macro and honestly my VBA is quite rusty (also not that good in VBA either). The problem i am having is the user is using the macro by selecting a row and using ctrl+L.

It does copy and insert a row with the right format, however some rows afterward seem empty (all blank and no row number) so you have to select the row > right click > display, for it to display properly

Not sure what to look for

Body:
The following code makes a new row below the row you want to copy then copies the format of the row and paste into the new row.

Sub Insertion_ligne_verrouillée()
  'Make a new row below active cell
  ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown,
  CopyOrigin:=xlFormatFromRightOrAbove
  'Copy the active row
  ActiveCell.EntireRow.Copy
  'paste format into new row
  ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
  Application.CutCopyMode = False
End Sub


问:
JSONObject how to store null value
I am using com.liferay.portal.kernel.json.JSONObject in liferay 6.2 and I want to store null value in an object of this type as mentioned below

```<code>`JSONObject jsonObject = JSONFactoryUtil.createJSONObject();`
`jsonObject.put("name","varun")`
`jsonObject.put("address",null)`
</code>```

As in org.json.JSONObject we can set null by JSONObject.NULL

Is there any way to set null in liferay JSONObject?

答:
The Liferay object wraps only the com.liferay.portal.json.JSONObjectImpl
As Tobias said you can use the JSONObject.NULL

Another thing is, do you really need to set this? Usually, parsers just null the fields if they don't find them.

Title: JSONObject how to store null value

Body:
I am using com.liferay.portal.kernel.json.JSONObject in liferay 6.2 and I want to store null value in an object of this type as mentioned below

`JSONObject jsonObject = JSONFactoryUtil.createJSONObject();`
`jsonObject.put("name","varun")`
`jsonObject.put("address",null)`

As in org.json.JSONObject we can set null by JSONObject.NULL

Is there any way to set null in liferay JSONObject?


答:
You cant do that reliably. If it was so easy, possible and reliable, then programmers would not be overloading operator=() and writing copy-constructor.

If you want to make a copy of your object, then either overload operator=(), or write copy-constructor, or do both!

Title: memcpy and C++ class templates - how to use it?

Body:
So.. How can we call something like
memcpy(dataCopy, data, length); to copy abstract data T?

Or if abstract T is not safe lets say we know that T is a POD (plain old data, basically a C struct) - is it possible to copy it?


问:
SQL Summing Group in a Group
I have two tables in a webSQL based Chrome extension:

The first table:

```<code>CREATE TABLE table1 (ID int, X int, Y int, tID int, vID int, Village varchar(50),
uID int, Player varchar(50), aID int, Alliance varchar(20), Population int)
</code>```

The second table:

```<code>CREATE TABLE table2 (ID int, Region varchar(20))
</code>```

Each entry in the first table is a village. The values of ID are unique and correspond to the same village, so each village also has a region, but these tables cannot (easily) be created as one table so I've gotten as far as using:

```<code>FROM (table1 LEFT JOIN table2 ON table1.ID = table2.ID)
</code>```

I want to get the sum of each alliance in each region, so the result looks something like:

```<code>Region      Alliance Name   Total Population/Region

REGION_A    Alliance_1      SUM(Alliance_1) in REGION_A
REGION_B    Alliance_1      SUM(Alliance_1) in REGION_B
REGION_B    Alliance_2      SUM(Alliance_2) in REGION_B
</code>```

...and so on.

答:
Try this</p>

```<code>select b.region, a.alliance, sum(a.population) from
table1 a join table2 b on a.aid=b.id group by b.region, a.alliance;
</code>```

Title: SQL Summing Group in a Group

Body:
I have two tables in a webSQL based Chrome extension:

The first table:

CREATE TABLE table1 (ID int, X int, Y int, tID int, vID int, Village varchar(50),
uID int, Player varchar(50), aID int, Alliance varchar(20), Population int)

The second table:

CREATE TABLE table2 (ID int, Region varchar(20))

Each entry in the first table is a village. The values of ID are unique and correspond to the same village, so each village also has a region, but these tables cannot (easily) be created as one table so I've gotten as far as using:

FROM (table1 LEFT JOIN table2 ON table1.ID = table2.ID)

I want to get the sum of each alliance in each region, so the result looks something like:

Region      Alliance Name   Total Population/Region

REGION_A    Alliance_1      SUM(Alliance_1) in REGION_A
REGION_B    Alliance_1      SUM(Alliance_1) in REGION_B
REGION_B    Alliance_2      SUM(Alliance_2) in REGION_B

...and so on.

Body:
Try this

select b.region, a.alliance, sum(a.population) from
table1 a join table2 b on a.aid=b.id group by b.region, a.alliance;


问:
Testing a TCL package; Tuning it for efficiency
I have written / rewritten a package and want to fully test it and do not know how to do so. Specifically when large amounts of data are loaded into the package it slows to a crawl.

I have posted the Code at wiki.tcl.tk

For the test assume that you have 12 columns & 10,000 rows.
where I run into an issue is Tcl2ExXML::outputXML.
How would you go about testing this and fixing where it is crawling at?

```<code>set Test_WB         "";
set Test_WS         "";
set ErrorHeadder    "";
set ErrorText       "";
set NormalHeadder   "";
set DateCol         "";

set Test_WB     [Tcl2ExXML::CreateWorkbook      "MassOrderLoad_[clock format [clock seconds] -format %Y%m%d%H%M%S]"]
set Test_WS     [Tcl2ExXML::CreateWorkSheet     $Test_WB "TestWS-[clock format [clock seconds] -format %Y-%m-%d]"]
set ErrorHeadder       [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -font {-nm "Calibri" -ff "Swiss" -sz 14 -fc #FF0000 -b 1} -border {{top bottom left} -ls "continuous" -lw 3} -interior {-ic #DCE6F1 -ip "Solid"}]
set ErrorText          [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -wrap 1 -font {-nm "Calibri" -ff "Swiss" -sz 11 -fc #FF0000}]
set NormalHeadder      [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -font {-nm "Calibri" -ff "Swiss" -sz 14 -fc #000000 -b 1} -border {-bp {top bottom} -ls "continuous" -lw 3 -bp {left right} -ls "continuous" -lw 1} -interior {-ic #DCE6F1 -ip "Solid"}]
set DateCol            [Tcl2ExXML::CreateStyle         $Test_WB -datafmt ymd]
                        Tcl2ExXML::setColumnAttributes $Test_WS 26 -s $DateCol
                        Tcl2ExXML::setColumnAttributes $Test_WS 27 -s $DateCol
set RowNum             [Tcl2ExXML::addRow $Test_WS -s $ErrorHeadder ERROR_MSG -s $NormalHeadder OPERATION  \
                                                   -s $NormalHeadder RowData_1 -s $NormalHeadder RowData_2 \
                                                   -s $NormalHeadder RowData_3 -s $NormalHeadder RowData_4 \
                                                   -s $NormalHeadder RowData_5 -s $NormalHeadder RowData_6 \
                                                   -s $NormalHeadder RowData_7 -s $NormalHeadder RowData_8 \
                                                   -s $NormalHeadder RowData_9 -s $NormalHeadder RowData_10]

foreach Row $DataList
    lassign $Row C1  C2  C3  C4  C5  C6  C7  C8  C9  C10 C11 C12
    set RowNum             [Tcl2ExXML::addRow $Test_WS -s $ErrorText $C1 $C2 $C3 $C4 $C5 $C6 $C7 $C8 $C9 $C10 $C11 $C12]
}

set XML [Tcl2ExXML::outputXML $Test_WB]
puts "XML Created, Cleaning up."
puts $Chan $XML
close $Chan

Tcl2ExXML::DeleteWorkbook $Test_WB
</code>```

答:
It's kind of a large thing you're asking for here and there's all sorts of things that could be issues. Could you split the problem up into smaller pieces and measure them on their own? Try to figure out where the critical problems are? (The time command will help you get some hard data.)

If the fundamental problem is just that the output is large, writing it to a temporary file might be the best option. But that's not necessarily going to help either.

Having scanned through, I see some potentially expensive operations. In particular, clock format and array names are not known for being cheap. Doesn't mean that they're the problem though. That drilling down step I mentioned above is critical.

Body:
I have written / rewritten a package and want to fully test it and do not know how to do so. Specifically when large amounts of data are loaded into the package it slows to a crawl.

I have posted the Code at wiki.tcl.tk

For the test assume that you have 12 columns & 10,000 rows.
where I run into an issue is Tcl2ExXML::outputXML.
How would you go about testing this and fixing where it is crawling at?

set Test_WB         "";
set Test_WS         "";
set ErrorHeadder    "";
set ErrorText       "";
set NormalHeadder   "";
set DateCol         "";

set Test_WB     [Tcl2ExXML::CreateWorkbook      "MassOrderLoad_[clock format [clock seconds] -format %Y%m%d%H%M%S]"]
set Test_WS     [Tcl2ExXML::CreateWorkSheet     $Test_WB "TestWS-[clock format [clock seconds] -format %Y-%m-%d]"]
set ErrorHeadder       [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -font {-nm "Calibri" -ff "Swiss" -sz 14 -fc #FF0000 -b 1} -border {{top bottom left} -ls "continuous" -lw 3} -interior {-ic #DCE6F1 -ip "Solid"}]
set ErrorText          [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -wrap 1 -font {-nm "Calibri" -ff "Swiss" -sz 11 -fc #FF0000}]
set NormalHeadder      [Tcl2ExXML::CreateStyle         $Test_WB -algnmt {-v bottom -h center} -font {-nm "Calibri" -ff "Swiss" -sz 14 -fc #000000 -b 1} -border {-bp {top bottom} -ls "continuous" -lw 3 -bp {left right} -ls "continuous" -lw 1} -interior {-ic #DCE6F1 -ip "Solid"}]
set DateCol            [Tcl2ExXML::CreateStyle         $Test_WB -datafmt ymd]
                        Tcl2ExXML::setColumnAttributes $Test_WS 26 -s $DateCol
                        Tcl2ExXML::setColumnAttributes $Test_WS 27 -s $DateCol
set RowNum             [Tcl2ExXML::addRow $Test_WS -s $ErrorHeadder ERROR_MSG -s $NormalHeadder OPERATION  \
                                                   -s $NormalHeadder RowData_1 -s $NormalHeadder RowData_2 \
                                                   -s $NormalHeadder RowData_3 -s $NormalHeadder RowData_4 \
                                                   -s $NormalHeadder RowData_5 -s $NormalHeadder RowData_6 \
                                                   -s $NormalHeadder RowData_7 -s $NormalHeadder RowData_8 \
                                                   -s $NormalHeadder RowData_9 -s $NormalHeadder RowData_10]

foreach Row $DataList
    lassign $Row C1  C2  C3  C4  C5  C6  C7  C8  C9  C10 C11 C12
    set RowNum             [Tcl2ExXML::addRow $Test_WS -s $ErrorText $C1 $C2 $C3 $C4 $C5 $C6 $C7 $C8 $C9 $C10 $C11 $C12]
}

set XML [Tcl2ExXML::outputXML $Test_WB]
puts "XML Created, Cleaning up."
puts $Chan $XML
close $Chan

Tcl2ExXML::DeleteWorkbook $Test_WB


问:
How to use two workbooks and their worksheets altogether
I am using two workbooks at a time. The first workbook is the current workbook and the second will be opened while programming execution. I have made the global objects of the workbooks and worksheets. I'm having issues with using the worksheets simultaneously. The error is ERROR: object variable or with block variable, not set. I have mentioned the error in the comment in the second subroutine.

```<code>Dim WB As Workbook
Dim WB2 As Workbook

Dim WKS As Worksheet
Dim WKS2 As Worksheet

Sub Button1_Click()
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    Set WB = ThisWorkbook
    WB.Activate

    fd.AllowMultiSelect = False
    fd.Title = "Provide a title here."
    fd.InitialFileName = ThisWorkbook.Path
    If fd.Show() = True Then
        strFile = fd.SelectedItems(1)
        Set WB2 = Workbooks.Open(strFile)
        Set WSK2 = WB2.Sheets("Schweitzer Analysis")
        CalculateGrades
    Else
        MsgBox ("No file selected")
    End If
End Sub

Sub CalculateGrades()
    ' first clear the contents where grades results can appear
    clearGradesContents

    Dim index As Integer ' for current sheet
    Dim index2 As Integer ' for student sheet
    Dim countCorrect As Integer ' to count no of correct answers

    index = 2
    index = 8
    countCorrect = 0

    ' this first error here
    ' ERROR: object variable or with block variable not set
    Set WKS = WB.ActiveSheet

    Do While index <= 21
        ' the SECOND error shows here
        If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then
            Count = Count + 1
        Else
            WKS.Cells(index, 5) = WKS2.Cells(index2, 3)
        End If

        If WKS.Cells(index, 3) = WKS2.Cells(index2, 4) Then
            Count = Count + 1
        Else
            WKS.Cells(index, 6) = WKS2.Cells(index2, 4)
        End If

        index2 = index2 + 1
        index = index + 1
    Loop

End Sub

Sub clearGradesContents()
    Range("E2:F21").Select
    Selection.ClearContents
    Range("I2:I3").Select
    Selection.ClearContents
End Sub
</code>```

答:
EDIT: sorry for the previous answer, I hadn't seen your global declarations on top and I was sure it was because you hadn't declare it.

I think the issue is the following:

```<code>[...]
Set WB = ThisWorkbook
WB.Activate '<-- WB is the active workbook now
[...]
Set WB2 = Workbooks.Open(strFile) '<-- WB2 is the active workbook now!
Set WSK2 = WB2.Sheets("Schweitzer Analysis")
CalculateGrades '<-- going to next macro
[...]
Set WKS = WB.ActiveSheet '<-- ERROR: WB2 is the active workbook. WB can't have an active sheet if it's not the active workbook
</code>```

Then of course, being WKS not correctly set, you can't execute this:

```<code>If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then
</code>```

I have no way to test it now, but I think that should be the issue.
To solve it,

If you really need WKS to be the ActiveSheet

```<code>Dim activeSheetName As String
...
Sub Button1Click()
    ...
    Set WB = ThisWorkbook
    WB.Activate
    activeSheetName = WB.ActiveSheet.Name
    ...
End Sub
Sub CalculateGrades()
    ...
    Set WKS = WB.Sheets(activeSheetName)
    ...
</code>```

If you already know the name of the sheet you need

Just write:

```<code>Set WKS = WB.Sheets("your sheet")
</code>```

instead of

```<code>Set WKS = WB.ActiveSheet
</code>```

Body:
I am using two workbooks at a time. The first workbook is the current workbook and the second will be opened while programming execution. I have made the global objects of the workbooks and worksheets. I'm having issues with using the worksheets simultaneously. The error is ERROR: object variable or with block variable, not set. I have mentioned the error in the comment in the second subroutine.

Dim WB As Workbook
Dim WB2 As Workbook

Dim WKS As Worksheet
Dim WKS2 As Worksheet

Sub Button1_Click()
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    Set WB = ThisWorkbook
    WB.Activate

    fd.AllowMultiSelect = False
    fd.Title = "Provide a title here."
    fd.InitialFileName = ThisWorkbook.Path
    If fd.Show() = True Then
        strFile = fd.SelectedItems(1)
        Set WB2 = Workbooks.Open(strFile)
        Set WSK2 = WB2.Sheets("Schweitzer Analysis")
        CalculateGrades
    Else
        MsgBox ("No file selected")
    End If
End Sub

Sub CalculateGrades()
    ' first clear the contents where grades results can appear
    clearGradesContents

    Dim index As Integer ' for current sheet
    Dim index2 As Integer ' for student sheet
    Dim countCorrect As Integer ' to count no of correct answers

    index = 2
    index = 8
    countCorrect = 0

    ' this first error here
    ' ERROR: object variable or with block variable not set
    Set WKS = WB.ActiveSheet

    Do While index <= 21
        ' the SECOND error shows here
        If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then
            Count = Count + 1
        Else
            WKS.Cells(index, 5) = WKS2.Cells(index2, 3)
        End If

        If WKS.Cells(index, 3) = WKS2.Cells(index2, 4) Then
            Count = Count + 1
        Else
            WKS.Cells(index, 6) = WKS2.Cells(index2, 4)
        End If

        index2 = index2 + 1
        index = index + 1
    Loop

End Sub

Sub clearGradesContents()
    Range("E2:F21").Select
    Selection.ClearContents
    Range("I2:I3").Select
    Selection.ClearContents
End Sub

Body:
EDIT: sorry for the previous answer, I hadn't seen your global declarations on top and I was sure it was because you hadn't declare it.

I think the issue is the following:

[...]
Set WB = ThisWorkbook
WB.Activate '<-- WB is the active workbook now
[...]
Set WB2 = Workbooks.Open(strFile) '<-- WB2 is the active workbook now!
Set WSK2 = WB2.Sheets("Schweitzer Analysis")
CalculateGrades '<-- going to next macro
[...]
Set WKS = WB.ActiveSheet '<-- ERROR: WB2 is the active workbook. WB can't have an active sheet if it's not the active workbook

Then of course, being WKS not correctly set, you can't execute this:

If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then

I have no way to test it now, but I think that should be the issue.
To solve it,

If you really need WKS to be the ActiveSheet

Dim activeSheetName As String
...
Sub Button1Click()
    ...
    Set WB = ThisWorkbook
    WB.Activate
    activeSheetName = WB.ActiveSheet.Name
    ...
End Sub
Sub CalculateGrades()
    ...
    Set WKS = WB.Sheets(activeSheetName)
    ...

If you already know the name of the sheet you need

Just write:

Set WKS = WB.Sheets("your sheet")

instead of

Set WKS = WB.ActiveSheet