问:
Is it possible remove span element node around text node without interrupting the cursor?
In the following structure:

```<code><div contenteditable="true">
    <span class="some-class">Hello</span>
    World <!-- no span here -->
    <span class="some-other-class">and good bye!</span>
</div>
</code>```

Is it possible to remove selected span elements, but not the text node, without interrupting the cursor position in the contenteditable div?

So even if the cursor is inside the span, keep the same text content, but just remove the span elements around it

For example if the styling of some-class is red text color and I put the cursor somewhere inside the word "Hello", then I want the styling to be gone and remove the wrapping span

答:
Here ya go!

    Hello
    world
    and good bye!
    test

```

Body:
In the following structure:

    Hello
    World
    and good bye!

Is it possible to remove selected span elements, but not the text node, without interrupting the cursor position in the contenteditable div?

So even if the cursor is inside the span, keep the same text content, but just remove the span elements around it

For example if the styling of some-class is red text color and I put the cursor somewhere inside the word "Hello", then I want the styling to be gone and remove the wrapping span

Body:
Here ya go!

<div contenteditable="true">
    <span class="some-class" style="color: red">Hello</span>
    <span class="some-class" style="color: blue">world</span>
    <span class="some-other-class" style="color: orange">and good bye!</span>
    <span style="color: green">test</span>
</div>

<script>
    const div = document.querySelector('div');

    const getSelection = () => {
        let offset = 0;
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        let start = range.startOffset;
        let end = range.endOffset;

        if (selection.baseNode.parentNode.hasChildNodes()) {
            for (const node of selection.baseNode.parentNode.childNodes) {
                const cnode = node;
                if (cnode.nodeType == document.TEXT_NODE && !(offset + cnode.length > start)) {
                    offset = offset + cnode.length;
                }
                if (cnode.nodeType == document.ELEMENT_NODE && !(offset + cnode.textContent.length > start)) {
                    offset = offset + cnode.textContent.length;
                }
            }
        }

        start = start + offset;
        end = end + offset;

        return { start, end };
    };

    const removeSpan = ({ target, currentTarget: { selectionStart } }) => {
        // Get our selection points for within our span element
        const { start, end } = getSelection();

        // Only run this logic for span elements
        if (target.tagName === 'SPAN') {
            // Create new text node from our span's innerText
            const text = document.createTextNode(target.innerText + ' ');

            // Replace span with just the text
            target.replaceWith(text);

            // Create a range and set selection range back to what it was to not affect cursor
            const range = document.createRange();
            range.setStart(text, start);
            range.setEnd(text, end);

            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
        }
    };

    div.addEventListener('click', removeSpan);
</script>


来源: stackexchange

问:
How do I pick random data from an array and make sure that a minimum of a certain data are selected from that array without effecting probability?
I am selecting randomly 20 bikes from a larger array of bikes, and then creating a new array with those selected bikes. I would like to make sure that at least 2 of the randomly selected bikes in that new array are the color red. More than 2 can be red, but at a minimum 2 should be. How is this achieved while making it fair to all of the randomly selected bikes?

Some example code:

```<code>const bikes = [
  { type: 'bmx', color: 'red' },
  { type: 'mountain', color: 'blue' },
  { type: 'bmx', color: 'yellow' },
  { type: 'mountain', color: 'black' },
  { type: 'bmx', color: 'red' },
  { type: 'bmx', color: 'purple' }
  ...more bikes
]

const getRandomBikes = () => {
  const randomBikes = []

//random select 20 bikes
    for(let i = 0; i < 20; i++) {
        randomBikes.push(bikes[Math.floor(Math.random() * bikes.length)])
   }

  return randomBikes
}

getRandomBikes()

</code>```

So pretty simple to return a random array. But now how would I make sure that the random bike array contained at least two bikes with color: 'red' without effecting the probability of every bike being selected? Presumably I would be running getRandomBikes() until the returned array satisfied the requirements, but say my array of bikes is 10000 long, that may take forever before the requirement is met. How do I ensure at least two red bikes end up in the randomly selected bike array?

答:
While iterating, you might count up the number of required bikes of a specific color remaining, and if equal to the number of items that remain to be chosen, pick only from the bikes with the right color.

const bikes = [
  { type: 'bmx', color: 'red' },
  { type: 'mountain', color: 'blue' },
  { type: 'bmx', color: 'yellow' },
  { type: 'mountain', color: 'black' },
  { type: 'bmx', color: 'red' },
  { type: 'bmx', color: 'purple' }
];

const getRandomBikes = (requiredRed, totalPicks) => {
  const chosenBikes = [];
  const reds = bikes.filter(({ color }) => color === 'red');
  for(let i = 0; i < totalPicks; i++) {
    const redsSoFar = chosenBikes.reduce((a, b) => a + (b.color === 'red'), 0);
    const picksRemaining = totalPicks - i;
    const mustChooseRed = requiredRed - redsSoFar === picksRemaining;
    chosenBikes.push(
       mustChooseRed
       ? reds[Math.floor(Math.random() * reds.length)]
       : bikes[Math.floor(Math.random() * bikes.length)]
    );
  }
  return chosenBikes;
}

console.log(getRandomBikes(2, 3));```
</div>
</div>
</p>
<p>Or with less complexity</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const bikes = [
  { type: 'bmx', color: 'red' },
  { type: 'mountain', color: 'blue' },
  { type: 'bmx', color: 'yellow' },
  { type: 'mountain', color: 'black' },
  { type: 'bmx', color: 'red' },
  { type: 'bmx', color: 'purple' }
];

const getRandomBikes = (requiredRed, totalPicks) => {
  const chosenBikes = [];
  const reds = bikes.filter(({ color }) => color === 'red');
  let redsSoFar = 0;
  for(let i = 0; i < totalPicks; i++) {
    const picksRemaining = totalPicks - i;
    const mustChooseRed = requiredRed - redsSoFar === picksRemaining;
    const chosenBike = mustChooseRed
       ? reds[Math.floor(Math.random() * reds.length)]
       : bikes[Math.floor(Math.random() * bikes.length)]
    if (chosenBike.color === 'red') redsSoFar++;
    chosenBikes.push(chosenBike);
  }
  return chosenBikes;
}

console.log(getRandomBikes(2, 3));</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am selecting randomly 20 bikes from a larger array of bikes, and then creating a new array with those selected bikes. I would like to make sure that at least 2 of the randomly selected bikes in that new array are the color red. More than 2 can be red, but at a minimum 2 should be. How is this achieved while making it fair to all of the randomly selected bikes?

Some example code:

const bikes = [
  { type: 'bmx', color: 'red' },
  { type: 'mountain', color: 'blue' },
  { type: 'bmx', color: 'yellow' },
  { type: 'mountain', color: 'black' },
  { type: 'bmx', color: 'red' },
  { type: 'bmx', color: 'purple' }
  ...more bikes
]

const getRandomBikes = () => {
  const randomBikes = []

//random select 20 bikes
    for(let i = 0; i < 20; i++) {
        randomBikes.push(bikes[Math.floor(Math.random() * bikes.length)])
   }

  return randomBikes
}

getRandomBikes()

So pretty simple to return a random array. But now how would I make sure that the random bike array contained at least two bikes with color: 'red' without effecting the probability of every bike being selected? Presumably I would be running getRandomBikes() until the returned array satisfied the requirements, but say my array of bikes is 10000 long, that may take forever before the requirement is met. How do I ensure at least two red bikes end up in the randomly selected bike array?

Body:
While iterating, you might count up the number of required bikes of a specific color remaining, and if equal to the number of items that remain to be chosen, pick only from the bikes with the right color.

const bikes = [
  { type: 'bmx', color: 'red' },
  { type: 'mountain', color: 'blue' },
  { type: 'bmx', color: 'yellow' },
  { type: 'mountain', color: 'black' },
  { type: 'bmx', color: 'red' },
  { type: 'bmx', color: 'purple' }
];

const getRandomBikes = (requiredRed, totalPicks) => {
  const chosenBikes = [];
  const reds = bikes.filter(({ color }) => color === 'red');
  for(let i = 0; i < totalPicks; i++) {
    const redsSoFar = chosenBikes.reduce((a, b) => a + (b.color === 'red'), 0);
    const picksRemaining = totalPicks - i;
    const mustChooseRed = requiredRed - redsSoFar === picksRemaining;
    chosenBikes.push(
       mustChooseRed
       ? reds[Math.floor(Math.random() * reds.length)]
       : bikes[Math.floor(Math.random() * bikes.length)]
    );
  }
  return chosenBikes;
}

console.log(getRandomBikes(2, 3));

Or with less complexity

const bikes = [
  { type: 'bmx', color: 'red' },
  { type: 'mountain', color: 'blue' },
  { type: 'bmx', color: 'yellow' },
  { type: 'mountain', color: 'black' },
  { type: 'bmx', color: 'red' },
  { type: 'bmx', color: 'purple' }
];

const getRandomBikes = (requiredRed, totalPicks) => {
  const chosenBikes = [];
  const reds = bikes.filter(({ color }) => color === 'red');
  let redsSoFar = 0;
  for(let i = 0; i < totalPicks; i++) {
    const picksRemaining = totalPicks - i;
    const mustChooseRed = requiredRed - redsSoFar === picksRemaining;
    const chosenBike = mustChooseRed
       ? reds[Math.floor(Math.random() * reds.length)]
       : bikes[Math.floor(Math.random() * bikes.length)]
    if (chosenBike.color === 'red') redsSoFar++;
    chosenBikes.push(chosenBike);
  }
  return chosenBikes;
}

console.log(getRandomBikes(2, 3));


问:
format data output inline
I need help

they need the results to be in a column

```<code>def part(n, k):
    def _part(n, k, pre):
        if n <= 0:
            return []
        if k == 1:
            if n <= pre:
                return [[n]]
            return []
        ret = []
        for i in range(min(pre, n), 0, -1):
            ret += [[i] + sub for sub in _part(n-i, k-1, i)]
        return ret
    return _part(n, k, n)

print(part(21, 2))
</code>```

the script gives results in this format

```<code>[[20, 1], [19, 2], [18, 3], [17, 4], [16, 5], [15, 6], [14, 7], [13, 8], [12, 9], [11, 10]]
</code>```

I need each result to be on the same line

example

```<code>20:1
19:2
18:3
17:4
16:5
15:6
14:7
13:8
12:9
</code>```

11:10

答:
You can simply do :

x = part(21,2)
for i in x:
   print(str(i[0])+':'+str(i[1]))
```

Title: format data output inline

Body:
I need help

they need the results to be in a column

def part(n, k):
    def _part(n, k, pre):
        if n <= 0:
            return []
        if k == 1:
            if n <= pre:
                return [[n]]
            return []
        ret = []
        for i in range(min(pre, n), 0, -1):
            ret += [[i] + sub for sub in _part(n-i, k-1, i)]
        return ret
    return _part(n, k, n)

print(part(21, 2))

the script gives results in this format

[[20, 1], [19, 2], [18, 3], [17, 4], [16, 5], [15, 6], [14, 7], [13, 8], [12, 9], [11, 10]]

I need each result to be on the same line

example

20:1
19:2
18:3
17:4
16:5
15:6
14:7
13:8
12:9

11:10


问:
nodejs - heroku - express-sessions
i'm building a website in nodejs with expressjs and i'm using express-sessions for handling the users sessions. here is my code.

on app.js file from where the app starts.

```<code>app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());

app.use(session(config.sessionConfig));

app.use(override());
</code>```

the config.sessionConfig object is here

```<code>  sessionConfig : {
    secret: 'shhSecrt',
    store: new MongoStore({ url:dbUrl+dbName}),
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
  }
</code>```

The problem is that when i deploy it to heroku the req.session variable doesnt seem to mantain its state.
To be more specificaly, when a user registers i store for example his username in the req.session.usernname variable but on the next request that the user does the req.session.username is undefined not because that is not stored on the db, but because the server can not recognize his session!
I dont know why, I have being trying to solve it for 2 days and i cant figure out. Also when i run the app in localhost everything works fine.
Please Help!!
thank you!

*let me know if you need more info or code sample.

答:
I was also facing the same problem and thought that maybe it's a bug... but i found that setting up the session like below

app.set('trust proxy', 1)
app.use(session({
  resave: false,
  saveUninitialized: true,
  secret: 'your secret text',
  cookie: {
    secure: (process.env.NODE_ENV && process.env.NODE_ENV == 'production') ? true:false
  }
}))
```

fixes the problem :D

ContentLicense: CC BY-SA 3.0

Title: nodejs - heroku - express-sessions

Body:
i'm building a website in nodejs with expressjs and i'm using express-sessions for handling the users sessions. here is my code.

on app.js file from where the app starts.

app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());

app.use(session(config.sessionConfig));

app.use(override());

the config.sessionConfig object is here

  sessionConfig : {
    secret: 'shhSecrt',
    store: new MongoStore({ url:dbUrl+dbName}),
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
  }

The problem is that when i deploy it to heroku the req.session variable doesnt seem to mantain its state.
To be more specificaly, when a user registers i store for example his username in the req.session.usernname variable but on the next request that the user does the req.session.username is undefined not because that is not stored on the db, but because the server can not recognize his session!
I dont know why, I have being trying to solve it for 2 days and i cant figure out. Also when i run the app in localhost everything works fine.
Please Help!!
thank you!

*let me know if you need more info or code sample.

Body:
I was also facing the same problem and thought that maybe it's a bug... but i found that setting up the session like below

app.set('trust proxy', 1)
app.use(session({
  resave: false,
  saveUninitialized: true,
  secret: 'your secret text',
  cookie: {
    secure: (process.env.NODE_ENV && process.env.NODE_ENV == 'production') ? true:false
  }
}))

fixes the problem :D


问:
Confusion about PowerBI Query Editor View Tab
I am going through the tutorial and I am a bit confused about the View Tab of the Query Editor.

In the tutorial it's presented as a panel where I would be able to select "Data View" and "Schema View" like here:

When I installed the Power BI Desktop (I tried both 32 and 64 bit versions from here).
I see following items in the View Tab:

I am a bit perplexed whether I am using the same product described in the tutorial since I don't see the expected "Data view" and "Schema view" options.

答:
The tutorial is basing snippets from the Power BI Service, as opposed to Power BI Desktop. Power BI Desktop is the downloadable software that you will use on your local machine. That being said, Power BI Service does allow users to develop reports in the Service. Development in the cloud (Power BI Service) will be very similar to development in Power BI Desktop (the local software), but there are some slight differences. Overall, I believe, Power BI Desktop has more functionality than Power BI Service when it comes to report development.

This may sound confusing, but really its pretty typical of Microsoft's app offerings. Think of Excel and Word, both of which have local software you can download and use. But they also have the minimalized functionality that exists in the cloud.

And to answer your question specifically, no, it appears that Power BI Desktop does not have those views at this time.


问:
Promise not resolving even with status of fulfilled and target data on PromiseResult
I need help on this issue I'm experiencing (I have already searched Stack overflow extensively but could not solve it on my own).

I have the following "dummy" logic to test async/await behaviour:

```<code>const data = [1, 2, 3]

async function newData() {
  return data
}

async function getData() {
  const fetchedData = await newData();
  return fetchedData
}

console.log(
  (async () => await getData())()
)
</code>```

Even though I have awaited for all Promise fulfillings, the following data is returned from the console log:

Console.log return

What am I doing wrong? Why doesn't the Promise return the value but remains pending even though it is 'fulfilled'?

Thanks in advance.

答:
All async functions return a promise.  That's why newData(), getData() and your async IIFE you have buried in a console.log() ALL return a promise.  When you return a value from an async function, that returned value just becomes the resolved value of the promise that the async function returns.  An async function NEVER returns the value directly.

So, even this:

```<code>(async () => await getData())()
</code>```

is an async function that returns a promise.

To get the resolved value from an async function, you MUST use .then() or await:

```<code>// this must be inside an async function or
// in an environment where top level await is allowed
console.log(await getData());
</code>```

or:

```<code>getData().then(result => {
    console.log(result);
});
</code>```

Body:
I need help on this issue I'm experiencing (I have already searched Stack overflow extensively but could not solve it on my own).

I have the following "dummy" logic to test async/await behaviour:

const data = [1, 2, 3]

async function newData() {
  return data
}

async function getData() {
  const fetchedData = await newData();
  return fetchedData
}

console.log(
  (async () => await getData())()
)

Even though I have awaited for all Promise fulfillings, the following data is returned from the console log:

Console.log return

What am I doing wrong? Why doesn't the Promise return the value but remains pending even though it is 'fulfilled'?

Thanks in advance.

Body:
All async functions return a promise.  That's why newData(), getData() and your async IIFE you have buried in a console.log() ALL return a promise.  When you return a value from an async function, that returned value just becomes the resolved value of the promise that the async function returns.  An async function NEVER returns the value directly.

So, even this:

(async () => await getData())()

is an async function that returns a promise.

To get the resolved value from an async function, you MUST use .then() or await:

// this must be inside an async function or
// in an environment where top level await is allowed
console.log(await getData());

or:

getData().then(result => {
    console.log(result);
});


问:
Windows CreateFile in C# Returns Invalid Handle
I am trying to invoke the CreateFile method from Kernel32.dll in a C# application, and it is returning an invalid handle everytime. I've looked all over and can't find a solution to this problem. Here is the relevant code:

Constants:

```<code>    const UInt64 GENERIC_READ = 0x80000000L;
    const UInt64 GENERIC_WRITE = 0x40000000L;
    const UInt64 GENERIC_EXECUTE = 0x20000000L;
    const UInt64 GENERIC_ALL = 0x10000000L;
    const uint FILE_SHARE_READ = 0x00000001;
    const uint FILE_SHARE_WRITE = 0x00000002;
    const uint OPEN_EXISTING = 0x00000003;
    const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
</code>```

Importing the Method:

```<code>[DllImport("kernel32.dll", SetLastError = true)]
    static extern unsafe SafeFileHandle CreateFile(
          string FileName,
          ulong DesiredAccess,
          uint ShareMode,
          IntPtr SecurityAttributes,
          uint CreationDisposition,
          uint FlagsAndAttributes,
          IntPtr hTemplateFile
          );
SafeFileHandle JFifoDrv = LoadDriver();
</code>```

Method to Load Driver:

```<code>unsafe private SafeFileHandle LoadDriver()
    {
        SafeFileHandle hDrv = (SafeFileHandle)null;
        try
        {
            hDrv = CreateFile("\\\\.\\JFIFODRV",
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                (IntPtr)null,
                OPEN_EXISTING,
                FILE_FLAG_DELETE_ON_CLOSE,
                (IntPtr)null);

            DriverLoaded = true;
        }
        catch
        {
            poll.Stop();
            DriverLoaded = false;
        }

        return hDrv;
    }
</code>```

Can Anyone help me figure out the problem?

答:
I'm pretty sure that "\\\\.\\JFIFODRV" is an invalid device name, and it is certainly not a valid file name.  Something like "\\\\.\\F:" should open the F: drive / partition, although I'm pretty sure this will fail if F: is mounted, as you are asking for write access.

What are you trying to open?

Also you should call Marshal.GetLastWin32Error - this will get an error code with more detail than just "it didn't work".

Body:
I am trying to invoke the CreateFile method from Kernel32.dll in a C# application, and it is returning an invalid handle everytime. I've looked all over and can't find a solution to this problem. Here is the relevant code:

Constants:

    const UInt64 GENERIC_READ = 0x80000000L;
    const UInt64 GENERIC_WRITE = 0x40000000L;
    const UInt64 GENERIC_EXECUTE = 0x20000000L;
    const UInt64 GENERIC_ALL = 0x10000000L;
    const uint FILE_SHARE_READ = 0x00000001;
    const uint FILE_SHARE_WRITE = 0x00000002;
    const uint OPEN_EXISTING = 0x00000003;
    const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;

Importing the Method:

[DllImport("kernel32.dll", SetLastError = true)]
    static extern unsafe SafeFileHandle CreateFile(
          string FileName,
          ulong DesiredAccess,
          uint ShareMode,
          IntPtr SecurityAttributes,
          uint CreationDisposition,
          uint FlagsAndAttributes,
          IntPtr hTemplateFile
          );
SafeFileHandle JFifoDrv = LoadDriver();

Method to Load Driver:

unsafe private SafeFileHandle LoadDriver()
    {
        SafeFileHandle hDrv = (SafeFileHandle)null;
        try
        {
            hDrv = CreateFile("\\\\.\\JFIFODRV",
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                (IntPtr)null,
                OPEN_EXISTING,
                FILE_FLAG_DELETE_ON_CLOSE,
                (IntPtr)null);

            DriverLoaded = true;
        }
        catch
        {
            poll.Stop();
            DriverLoaded = false;
        }

        return hDrv;
    }

Can Anyone help me figure out the problem?


问:
execute a command with each list from a text file
I would like to execute a command with each list from a text file. I tried doing this code but it is not giving me any output. Can you help me? Thank you!

```<code>for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i> new_"$i".fa

    cat > final.list
    echo -e "new_"$i"\t+" >> final.list
done
</code>```

list_of_text.txt looks like this

```<code>nameabc
namedef
nameghi
namejkl
</code>```

while final.list looks like this

```<code>new_nameabc.fa  +
new_namedef.fa  +
new_nameghi.fa  +
new_namejkl.fa  +
</code>```

In summary
the long version of the code is like this and I'm trying to make a shortcut:

```<code>commandtool some_input_file nameabc> new_nameabc.fa
commandtool some_input_file namedef> new_namedef.fa
commandtool some_input_file nameghi> new_nameghi.fa
commandtool some_input_file namejkl> new_namejkl.fa

echo -e "new_nameabc.fa\t+" > final.list
echo -e "new_namedef.fa\t+" >> final.list
echo -e "new_nameghi.fa\t+" >> final.list
echo -e "new_namejkl.fa\t+" >> final.list
</code>```

Edit: It is working now. I just replaced cat > final.list to echo > final.list and moved it at the beginning as suggested in the answer.

答:
Moving cat out of the loop and replacing with echo, I believe you want:

```<code>echo > final.list
for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i > new_"$i".fa
    echo -e "new_${i}.fa\t+" >> final.list
done
</code>```

Body:
I would like to execute a command with each list from a text file. I tried doing this code but it is not giving me any output. Can you help me? Thank you!

for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i> new_"$i".fa

    cat > final.list
    echo -e "new_"$i"\t+" >> final.list
done

list_of_text.txt looks like this

nameabc
namedef
nameghi
namejkl

while final.list looks like this

new_nameabc.fa  +
new_namedef.fa  +
new_nameghi.fa  +
new_namejkl.fa  +

In summary
the long version of the code is like this and I'm trying to make a shortcut:

commandtool some_input_file nameabc> new_nameabc.fa
commandtool some_input_file namedef> new_namedef.fa
commandtool some_input_file nameghi> new_nameghi.fa
commandtool some_input_file namejkl> new_namejkl.fa

echo -e "new_nameabc.fa\t+" > final.list
echo -e "new_namedef.fa\t+" >> final.list
echo -e "new_nameghi.fa\t+" >> final.list
echo -e "new_namejkl.fa\t+" >> final.list

Edit: It is working now. I just replaced cat > final.list to echo > final.list and moved it at the beginning as suggested in the answer.

Body:
Moving cat out of the loop and replacing with echo, I believe you want:

echo > final.list
for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i > new_"$i".fa
    echo -e "new_${i}.fa\t+" >> final.list
done


问:
I am getting a white empty page when opening this vue view (HTML)
I am working on a simple ToDo List.
I have a problem: When opening the EditAssignee.vue in the browser I am getting an empty, white page. Only my header is displayed. Can anyone tell me, where the problem is? Is there something wrong with my router?
Be warned: I'm pretty new to this...
Thank you!

EditAssignee.vue

```<code><template>
  <div>
    <h1>Edit Assignee</h1>
<!--    <h2>{{ this.assignee.prename }} {{ this.assignee.name }}</h2>-->
<!--    <p>{{ this.assignee.email }}</p>-->
    <br>
    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    <b-button size="sm" variant="primary" v-on:click="updateAssignee">Save Changes</b-button>
  </div>

</template>

<script>
import axios from "axios";
import config from "@/config";

export default {
  name: "EditAssignee",
  data() {
    return {
      assignee: null,
      id: this.$route.params.id,
      prename: this.$route.params.prename,
      email: this.$route.params.email,
      name: this.$route.params.name,
      assignees: []
    }
  },

  methods: {
    getAssignee: function () {
      axios.get(`${config.apiBaseUrl}/assignees/${this.$route.params.id}`).then((response) => {
        // log response data to the browser console
        console.log(response.data);
        // assign response to data variable
        this.assignee = response.data;
      });
    },
    updateAssignee: function () {
      axios.put(`${config.apiBaseUrl}/assignees/${this.$route.params.id}`, {
        prename: this.prename,
        name: this.name,
        email: this.email
      })
          .then(response => {
            this.fetchAllAssignees();

            console.log(response)
          })
          .catch(error => console.log(error))
    },

    created: function () {
      this.getAssignee()
    }
  }
}
</script>

<style scoped>

</style>

</code>```

Assignee.vue (Here's the button to the EditAssignee page)

```<code><template>
  <div>
    <h1>Assignees</h1>

    <p>Please fill in all fields to create a new assignee. Please note that the assignee needs an email with the domain
      <i>.uni-stuttgart.de.</i></p>
    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    <b-button variant="primary" size="sm" v-on:click="createAssignee"
    >Create new Assignee
    </b-button>
    <br><br>

    <b-alert v-bind:show="assignees.length === 0" variant="warning">
      No assignee available on the server...
    </b-alert>

    <div class="assigneeBox" v-for="assignee in assignees" v-bind:key="assignee.id">
      <h3>{{ assignee.prename }} {{ assignee.name }}</h3>
      <p>E-Mail: {{ assignee.email }}, ID: {{ assignee.id }}</p>

      <div>
        <b-button
            size="sm"
            variant="outline-danger"
            v-on:click="deleteAssignee(assignee.id)"
        >
          <b-icon-trash></b-icon-trash>
          Delete
        </b-button>

        <b-button size="sm" variant="primary" :to="`/assignees/${assignee.id}`"><b-icon-pencil></b-icon-pencil>
          Details & Edit
        </b-button>

        <hr>
      </div>

    </div>
  </div>
</template>

<script>
// import configuration with API url; @ refers to the src directory
import config from "@/config";
// import library for HTTP requests
import axios from "axios";

export default {
  name: "Assignees",
  data() {
    return {
      assignees: [],
      prename: this.$route.params.prename,
      email: this.$route.params.email,
      name: this.$route.params.name,
      deleteMessage: ""
    };
  },
  methods: {
    // send GET request to API to fetch all assignees
    fetchAllAssignees: function () {
      axios.get(`${config.apiBaseUrl}/assignees`).then((response) => {
        // log response data to the browser console
        console.log(response.data);
        // assign response to data variable
        this.assignees = response.data;
      });
    },
    deleteAssignee: function (id) {
      // send DELETE request to API to delete a specific assignee by ID
      axios.delete(`${config.apiBaseUrl}/assignees/${id}`).then(() => {
        // update view by removing deleted assignee
        this.assignees = this.assignees.filter((assignee) => assignee.id !== id);
        // show success message using BootstrapVue toast component
        this.showToastMessage(
            "Alert",
            `Successfully deleted assignee with ID ${id}!`,
            "success"
        );
      });
    },
    createAssignee() {
      axios.post(`${config.apiBaseUrl}/assignees`, {prename: this.prename, name: this.name, email: this.email})
          .then(response => {
            this.fetchAllAssignees()
            this.showToastMessage(
                "Created",
                `${this.prename} ${this.name} has been created`,
                "success"
            );
            console.log(response)
          })
          .catch(error => console.log(error))
    },
    showToastMessage(title, msg, variant) {
      this.$bvToast.toast(msg, {
        title: title,
        variant: variant,
        solid: true,
        toaster: "b-toaster-top-center",
        autoHideDelay: 4000,
        appendToast: true
      });
    }
  },
  // executed after the component has been started
  created: function () {
    this.fetchAllAssignees();
  }
};
</script>

<style>
.assigneesBox {
  padding: 10px;
  margin: 3px;
  border: 1px solid #42b983;
  float: left;
  min-width: 250px;
  text-align: center;
}

.assigneesLogo {
  height: 200px;
}

.assigneeBox button {
  margin: 5px;
}
</style>
</code>```

Errors:

```<code>vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read properties of null (reading 'prename')"

found in

---> <EditAssignee> at src/views/EditAssignee.vue
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1893
globalHandleError @ vue.runtime.esm.js?2b0e:1888
handleError @ vue.runtime.esm.js?2b0e:1848
Vue._render @ vue.runtime.esm.js?2b0e:3571
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
Watcher @ vue.runtime.esm.js?2b0e:4484
mountComponent @ vue.runtime.esm.js?2b0e:4088
Vue.$mount @ vue.runtime.esm.js?2b0e:8459
init @ vue.runtime.esm.js?2b0e:3137
merged @ vue.runtime.esm.js?2b0e:3322
createComponent @ vue.runtime.esm.js?2b0e:6022
createElm @ vue.runtime.esm.js?2b0e:5969
updateChildren @ vue.runtime.esm.js?2b0e:6260
patchVnode @ vue.runtime.esm.js?2b0e:6363
updateChildren @ vue.runtime.esm.js?2b0e:6237
patchVnode @ vue.runtime.esm.js?2b0e:6363
patch @ vue.runtime.esm.js?2b0e:6526
Vue._update @ vue.runtime.esm.js?2b0e:3963
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
run @ vue.runtime.esm.js?2b0e:4570
flushSchedulerQueue @ vue.runtime.esm.js?2b0e:4326
eval @ vue.runtime.esm.js?2b0e:1989
flushCallbacks @ vue.runtime.esm.js?2b0e:1915
Promise.then (async)
timerFunc @ vue.runtime.esm.js?2b0e:1942
nextTick @ vue.runtime.esm.js?2b0e:1999
queueWatcher @ vue.runtime.esm.js?2b0e:4418
update @ vue.runtime.esm.js?2b0e:4560
notify @ vue.runtime.esm.js?2b0e:730
reactiveSetter @ vue.runtime.esm.js?2b0e:1055
eval @ vue-router.esm.js?8c4f:3003
eval @ vue-router.esm.js?8c4f:3002
updateRoute @ vue-router.esm.js?8c4f:2414
eval @ vue-router.esm.js?8c4f:2263
eval @ vue-router.esm.js?8c4f:2402
step @ vue-router.esm.js?8c4f:2001
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
eval @ vue-router.esm.js?8c4f:2397
step @ vue-router.esm.js?8c4f:2001
eval @ vue-router.esm.js?8c4f:2005
eval @ vue-router.esm.js?8c4f:2384
eval @ vue-router.esm.js?8c4f:2162
iterator @ vue-router.esm.js?8c4f:2362
step @ vue-router.esm.js?8c4f:2004
step @ vue-router.esm.js?8c4f:2008
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
confirmTransition @ vue-router.esm.js?8c4f:2392
transitionTo @ vue-router.esm.js?8c4f:2260
push @ vue-router.esm.js?8c4f:2715
push @ vue-router.esm.js?8c4f:3037
handler @ vue-router.esm.js?8c4f:1139
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
28 weitere Frames anzeigen
vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of null (reading 'prename')
    at Proxy.render (EditAssignee.vue?be9f:11:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4081:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)
    at mountComponent (vue.runtime.esm.js?2b0e:4088:1)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8459:1)
    at init (vue.runtime.esm.js?2b0e:3137:1)
    at merged (vue.runtime.esm.js?2b0e:3322:1)
    at createComponent (vue.runtime.esm.js?2b0e:6022:1)
</code>```

答:
The error log means that you are trying to read an attribute on an null object. The assignee is obtained from the network. Before the network request occurs, the Vue starts to read attributes. In this case, the assignee is still null. Therefore, before accessing an object that may be null, check whether the object is null.
In addition, this is not required for {{}}.</p>
```<code><h2>{{ assignee?`${assignee.prename} ${assignee.name}`:'' }}</h2>
<p>{{ assignee?assignee.email:'' }}</p>
</code>```

Body:
I am working on a simple ToDo List.
I have a problem: When opening the EditAssignee.vue in the browser I am getting an empty, white page. Only my header is displayed. Can anyone tell me, where the problem is? Is there something wrong with my router?
Be warned: I'm pretty new to this...
Thank you!

EditAssignee.vue

<template>

Edit Assignee

    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    Save Changes

</template>

Assignee.vue (Here's the button to the EditAssignee page)

<template>

Assignees

Please fill in all fields to create a new assignee. Please note that the assignee needs an email with the domain
      .uni-stuttgart.de.

    <input type="text" placeholder="Prename" v-model="prename"/>
    <input type="text" placeholder="Name" v-model="name"/>
    <input type="text" placeholder="E-Mail" v-model="email"/>
    Create new Assignee

      No assignee available on the server...

{{ assignee.prename }} {{ assignee.name }}

E-Mail: {{ assignee.email }}, ID: {{ assignee.id }}

          Delete

        <b-button size="sm" variant="primary" :to="`/assignees/${assignee.id}`">
          Details & Edit

</template>

Errors:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read properties of null (reading 'prename')"

found in

---> <EditAssignee> at src/views/EditAssignee.vue
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1893
globalHandleError @ vue.runtime.esm.js?2b0e:1888
handleError @ vue.runtime.esm.js?2b0e:1848
Vue._render @ vue.runtime.esm.js?2b0e:3571
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
Watcher @ vue.runtime.esm.js?2b0e:4484
mountComponent @ vue.runtime.esm.js?2b0e:4088
Vue.$mount @ vue.runtime.esm.js?2b0e:8459
init @ vue.runtime.esm.js?2b0e:3137
merged @ vue.runtime.esm.js?2b0e:3322
createComponent @ vue.runtime.esm.js?2b0e:6022
createElm @ vue.runtime.esm.js?2b0e:5969
updateChildren @ vue.runtime.esm.js?2b0e:6260
patchVnode @ vue.runtime.esm.js?2b0e:6363
updateChildren @ vue.runtime.esm.js?2b0e:6237
patchVnode @ vue.runtime.esm.js?2b0e:6363
patch @ vue.runtime.esm.js?2b0e:6526
Vue._update @ vue.runtime.esm.js?2b0e:3963
updateComponent @ vue.runtime.esm.js?2b0e:4081
get @ vue.runtime.esm.js?2b0e:4495
run @ vue.runtime.esm.js?2b0e:4570
flushSchedulerQueue @ vue.runtime.esm.js?2b0e:4326
eval @ vue.runtime.esm.js?2b0e:1989
flushCallbacks @ vue.runtime.esm.js?2b0e:1915
Promise.then (async)
timerFunc @ vue.runtime.esm.js?2b0e:1942
nextTick @ vue.runtime.esm.js?2b0e:1999
queueWatcher @ vue.runtime.esm.js?2b0e:4418
update @ vue.runtime.esm.js?2b0e:4560
notify @ vue.runtime.esm.js?2b0e:730
reactiveSetter @ vue.runtime.esm.js?2b0e:1055
eval @ vue-router.esm.js?8c4f:3003
eval @ vue-router.esm.js?8c4f:3002
updateRoute @ vue-router.esm.js?8c4f:2414
eval @ vue-router.esm.js?8c4f:2263
eval @ vue-router.esm.js?8c4f:2402
step @ vue-router.esm.js?8c4f:2001
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
eval @ vue-router.esm.js?8c4f:2397
step @ vue-router.esm.js?8c4f:2001
eval @ vue-router.esm.js?8c4f:2005
eval @ vue-router.esm.js?8c4f:2384
eval @ vue-router.esm.js?8c4f:2162
iterator @ vue-router.esm.js?8c4f:2362
step @ vue-router.esm.js?8c4f:2004
step @ vue-router.esm.js?8c4f:2008
step @ vue-router.esm.js?8c4f:2008
runQueue @ vue-router.esm.js?8c4f:2012
confirmTransition @ vue-router.esm.js?8c4f:2392
transitionTo @ vue-router.esm.js?8c4f:2260
push @ vue-router.esm.js?8c4f:2715
push @ vue-router.esm.js?8c4f:3037
handler @ vue-router.esm.js?8c4f:1139
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
28 weitere Frames anzeigen
vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of null (reading 'prename')
    at Proxy.render (EditAssignee.vue?be9f:11:1)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4081:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)
    at mountComponent (vue.runtime.esm.js?2b0e:4088:1)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8459:1)
    at init (vue.runtime.esm.js?2b0e:3137:1)
    at merged (vue.runtime.esm.js?2b0e:3322:1)
    at createComponent (vue.runtime.esm.js?2b0e:6022:1)

Body:
The error log means that you are trying to read an attribute on an null object. The assignee is obtained from the network. Before the network request occurs, the Vue starts to read attributes. In this case, the assignee is still null. Therefore, before accessing an object that may be null, check whether the object is null.
In addition, this is not required for {{}}.

<h2>{{ assignee?`${assignee.prename} ${assignee.name}`:'' }}</h2>
<p>{{ assignee?assignee.email:'' }}</p>


问:
How can i separate this div overlap
I am trying to build a web form and the divs keep overlapping.
I am confused as to why.
I have separated all into separate divs and I'm trying to have them stack one after the other.
How can I get all the divs to be in separate rows such that it doesnt overlap.

This is the component.html file:

```<code><div>
    <!--Navbar-->
    <mat-toolbar color="primary">

        <div class="centerNavBar">
            <a mat-button href="fa-dashboard">Back</a>

            <span class="headSpacer">Damage Assessment Tool</span>

            <a mat-button href="">Logout</a>
        </div>
    </mat-toolbar>
</div>

<div>
    <mat-sidenav-container class="MainContainter">
        <!--SideNav-->
        <mat-sidenav mode="side" opened>
            <div>
                <a mat-button href="">Message Board</a>
            </div>
        </mat-sidenav>
        <mat-sidenav-content class="MainContent">
            <mat-card>
                <mat-card-header class="sect">Create report:</mat-card-header>
                <br><br>
                <mat-card-content>
                    <!--Div for form-->
                    <div>
                        <mat-form-field>
                            <input
                                #MOCDateInput
                                matInput type= "Date"
                                required>
                        </mat-form-field>
                            <br>
                        <mat-form-field>
                            <mat-label>Comment</mat-label>
                            <input
                                #DescriptionInput
                                placeholder="--"
                                matInput type= "string"
                                required>
                        </mat-form-field>
                        <br>
                        <mat-form-field>
                        <mat-label>Facility In Question</mat-label>
                        <input
                                #MOCFacilityInput
                                placeholder="--"
                                matInput type= "string"
                                required>
                        </mat-form-field>
                        <br>
                        <br>
                    </div>
                    <div class="MOCMap">
                        <!--Div for Map-->
                        <div class="map-container">
                            <div class="map-frame">
                                <div id="map"></div>
                            </div>
                        </div>
                    </div>
                    <!--Div for buttons-->
                    <div>
                        <input
                            style="display: none;"
                            #ImageInput
                            type= "file"
                            (change)="onFileSelected($event)">
                        <br>
                        <br>
                        <button mat-raised-button type="button" (click)="ImageInput.click()">Upload An Image</button>

                        <button mat-raised-button
                        type="submit"
                        (click)="createMOCForm(MOCFacilityInput.value, DescriptionInput.value, MOCDateInput.value)" color="primary">Submit Report</button>
                    </div>
                </mat-card-content>
            </mat-card>
        </mat-sidenav-content>
    </mat-sidenav-container>
</div>
</code>```

The image shows the overlap

This is the global css file:

```<code>/* You can add global styles to this file, and also import other style files */
@import "~leaflet/dist/leaflet.css";

html, body {height: 100%}

body {
    margin: 0;
    font-family: Roboto;
    background-color: ghostwhite;
}

.sect{
    display: block;
    margin-top: auto;
    margin-left: auto;
    margin-right: auto;
    width: 850px;
    background-color: white;
}

.centerNavBar {
    margin: auto;
    width: auto;
    padding: auto;
}

.headSpacer{
    margin-left: 100px;
    margin-right: 100px;
}

/*map*/
.map-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 50px;
}

.map-frame {
    border: 2px solid black;
    height: 100%;
    width: 50%;
}

#map {
    height: 100%;
}
</code>```

Any help would be appreciate, thank you in advance.

答:
You want it to be laid out as

Form

Map

Buttons

Correct? It seems that only the map is a problem. Try removing the position: absolute and associated styles, your .map-container should look like this:

```<code>.map-container {
  margin: 50px;
}
</code>```

Setting position:absolute is causing the map to appear in the middle of the page, and disregard any layout. position:absolute puts the map some place relative to the nearest parent element with postition set to something.

Title: How can i separate this div overlap

Body:
I am trying to build a web form and the divs keep overlapping.
I am confused as to why.
I have separated all into separate divs and I'm trying to have them stack one after the other.
How can I get all the divs to be in separate rows such that it doesnt overlap.

This is the component.html file:

    <mat-toolbar color="primary">

            Back

            Damage Assessment Tool

            Logout

    </mat-toolbar>

    <mat-sidenav-container class="MainContainter">

        <mat-sidenav mode="side" opened>

                Message Board

        </mat-sidenav>
        <mat-sidenav-content class="MainContent">
            <mat-card>
                <mat-card-header class="sect">Create report:</mat-card-header>

                <mat-card-content>

                        <mat-form-field>
                            <input
                                #MOCDateInput
                                matInput type= "Date"
                                required>
                        </mat-form-field>

                        <mat-form-field>
                            <mat-label>Comment</mat-label>
                            <input
                                #DescriptionInput
                                placeholder="--"
                                matInput type= "string"
                                required>
                        </mat-form-field>

                        <mat-form-field>
                        <mat-label>Facility In Question</mat-label>
                        <input
                                #MOCFacilityInput
                                placeholder="--"
                                matInput type= "string"
                                required>
                        </mat-form-field>

                        <input
                            style="display: none;"
                            #ImageInput
                            type= "file"
                            (change)="onFileSelected($event)">

                        <button mat-raised-button type="button" (click)="ImageInput.click()">Upload An Image</button>

                        <button mat-raised-button
                        type="submit"
                        (click)="createMOCForm(MOCFacilityInput.value, DescriptionInput.value, MOCDateInput.value)" color="primary">Submit Report</button>

                </mat-card-content>
            </mat-card>
        </mat-sidenav-content>
    </mat-sidenav-container>

The image shows the overlap

This is the global css file:

/* You can add global styles to this file, and also import other style files */
@import "~leaflet/dist/leaflet.css";

html, body {height: 100%}

body {
    margin: 0;
    font-family: Roboto;
    background-color: ghostwhite;
}

.sect{
    display: block;
    margin-top: auto;
    margin-left: auto;
    margin-right: auto;
    width: 850px;
    background-color: white;
}

.centerNavBar {
    margin: auto;
    width: auto;
    padding: auto;
}

.headSpacer{
    margin-left: 100px;
    margin-right: 100px;
}

/*map*/
.map-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 50px;
}

.map-frame {
    border: 2px solid black;
    height: 100%;
    width: 50%;
}

#map {
    height: 100%;
}

Any help would be appreciate, thank you in advance.

Body:
You want it to be laid out as

Form

Map

Buttons

Correct? It seems that only the map is a problem. Try removing the position: absolute and associated styles, your .map-container should look like this:

.map-container {
  margin: 50px;
}

Setting position:absolute is causing the map to appear in the middle of the page, and disregard any layout. position:absolute puts the map some place relative to the nearest parent element with postition set to something.


问:
Asking the user for input until they give a valid response
I am writing a program that accepts user input.

```<code>#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")
</code>```

The program works as expected as long as the the user enters meaningful data.

Please enter your age: 23
You are able to vote in the United States!
```
<p>But it fails if the user enters invalid data:</p>
<pre class="lang-none prettyprint-override"><code>Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in <module>
    age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'
</code>```

Instead of crashing, I would like the program to ask for the input again. Like this:

Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!
```

How do I ask for valid input instead of crashing or accepting invalid values (e.g. -1)?

答:
You can try to convert it to a integer, but ask the user to repeat if it doesn't work.

```<code>while True:
    age = input('Please enter your age: ')
    try:
        age_int = int(age)
        if age_int >= 18:
            print('You can vote in the United States!')
        else:
            print('You cannot vote in the United States.')
        break
    except:
        print('Please enter a meaningful answer.')

</code>```

The while loop runs as long as the user has not inputted a meaningful answer, but breaks if it makes sense.

Body:
I am writing a program that accepts user input.

#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

The program works as expected as long as the the user enters meaningful data.

Please enter your age: 23
You are able to vote in the United States!

But it fails if the user enters invalid data:

Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in <module>
    age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'

Instead of crashing, I would like the program to ask for the input again. Like this:

Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!

How do I ask for valid input instead of crashing or accepting invalid values (e.g. -1)?

Body:
You can try to convert it to a integer, but ask the user to repeat if it doesn't work.

while True:
    age = input('Please enter your age: ')
    try:
        age_int = int(age)
        if age_int >= 18:
            print('You can vote in the United States!')
        else:
            print('You cannot vote in the United States.')
        break
    except:
        print('Please enter a meaningful answer.')

The while loop runs as long as the user has not inputted a meaningful answer, but breaks if it makes sense.


问:
How do I iterate through only the objects I have loaded into an array without iterating through the entire array?
I'm minoring in computer science at university, and need to write a program with three components:

A "Circle" class that defines methods for creating and working with a Circle object that has a radius and color as defined attributes in the object.

A "CircleMgr" class that manages an array of circle objects.

A "CircleApp" class that produces output for the program.

An issue I'm having (which is causing a runtime error) has been identified by my professor as lying inside the CircleApp class at line 53, which is a for loop iterating through the list--the code is as follows*:

```<code>for(int i = 0; i < mainList.length; i++){
        System.out.println("Circle " + i);
        System.out.println(mainList[i].getRadius());
        System.out.println(mainList[i].getColor());
    }
</code>```

Earlier in the program, I load the list created and managed by CircleMgr into mainList, which is contained in CircleApp. According to my professor, I need to iterate through only the objects that have been loaded into mainList (which will never be completely filled because we were told to create the object array at a size much larger than what the input file takes in). Unfortunately, I'm not certain how I could iterate through the array in a different manner; is anyone able to provide guidance to this effect?

*(the println statements are there to ensure that the output is correct before I format it, once I am able to move past the runtime error and actually produce output).

答:
You need a count of how many things are stored in the array.

Then, use the count in the loop condition as below.

```<code>for(int i = 0; i < count; i++){
        System.out.println("Circle " + i);
        System.out.println(mainList[i].getRadius());
        System.out.println(mainList[i].getColor());
    }
</code>```

Body:
I'm minoring in computer science at university, and need to write a program with three components:

A "Circle" class that defines methods for creating and working with a Circle object that has a radius and color as defined attributes in the object.

A "CircleMgr" class that manages an array of circle objects.

A "CircleApp" class that produces output for the program.

An issue I'm having (which is causing a runtime error) has been identified by my professor as lying inside the CircleApp class at line 53, which is a for loop iterating through the list--the code is as follows*:

for(int i = 0; i < mainList.length; i++){
        System.out.println("Circle " + i);
        System.out.println(mainList[i].getRadius());
        System.out.println(mainList[i].getColor());
    }

Earlier in the program, I load the list created and managed by CircleMgr into mainList, which is contained in CircleApp. According to my professor, I need to iterate through only the objects that have been loaded into mainList (which will never be completely filled because we were told to create the object array at a size much larger than what the input file takes in). Unfortunately, I'm not certain how I could iterate through the array in a different manner; is anyone able to provide guidance to this effect?

*(the println statements are there to ensure that the output is correct before I format it, once I am able to move past the runtime error and actually produce output).

Body:
You need a count of how many things are stored in the array.

Then, use the count in the loop condition as below.

for(int i = 0; i < count; i++){
        System.out.println("Circle " + i);
        System.out.println(mainList[i].getRadius());
        System.out.println(mainList[i].getColor());
    }


问:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.

Please stop posting:

CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.

3rd party services that allow a request to circumvent CORS

Command line options for turning off CORS for various browsers

I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:

XMLHttpRequest cannot load http://myApiUrl/login.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
```
<p>I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?</p>
<p>This is the request code:</p>
<pre class="lang-js prettyprint-override"><code>$.ajax({
  type: 'POST',
  dataType: 'text',
  url: api,
  username: 'user',
  password: 'pass',
  crossDomain: true,
  xhrFields: {
    withCredentials: true,
  },
})
  .done(function (data) {
    console.log('done');
  })
  .fail(function (xhr, textStatus, errorThrown) {
    alert(xhr.responseText);
    alert(textStatus);
  });
</code>```

答:
Your IP address is not whitelisted, so you are getting this error.
Ask the backend staff to whitelist your IP address for the service you are accessing.

Access-Control-Allow-Headers

Body:
Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.

Please stop posting:

CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.

3rd party services that allow a request to circumvent CORS

Command line options for turning off CORS for various browsers

I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:

XMLHttpRequest cannot load http://myApiUrl/login.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?

This is the request code:

$.ajax({
  type: 'POST',
  dataType: 'text',
  url: api,
  username: 'user',
  password: 'pass',
  crossDomain: true,
  xhrFields: {
    withCredentials: true,
  },
})
  .done(function (data) {
    console.log('done');
  })
  .fail(function (xhr, textStatus, errorThrown) {
    alert(xhr.responseText);
    alert(textStatus);
  });


问:
identifier "Node" is undefined in Linked list
This is my program to insert linked lists and print them. I'm getting error in void Insert(int x) function where I point temp variable to a new node. The error its showing is identifier "Node" is undefined. What am I supposed to do?

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

struct Node{
    int data;
    struct Node *next;
};
struct Node* head;  //global variable head

void Insert(int x){

    struct Node* temp=(Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;  //it is the same as temp->next=NULL
    head=temp;

}

void Print(){
    struct Node* temp = head;
    printf("List is: ");
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

int main() {
    head = NULL;
    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%d",&x);
        Insert(x);
        Print();
    }

    return 0;
}
</code>```

答:
You cast the void* returned by malloc to Node*, but there is no Node type.

Here:

```<code>struct Node* temp=(Node*)malloc(sizeof(struct Node));
//                ^^^^^^^
</code>```

You also do not need to cast the return from malloc. Example:

```<code>struct Node* temp = malloc(sizeof *temp);
</code>```

If you'd like to use Node instead of struct Node, you can typedefine it:

```<code>typedef struct Node Node;

struct Node {
    int data;
    Node *next; // struct not needed because Node is `typedef`ined
};
</code>```

You could then also do:

```<code>Node* temp = malloc(sizeof *temp);
</code>```

Body:
This is my program to insert linked lists and print them. I'm getting error in void Insert(int x) function where I point temp variable to a new node. The error its showing is identifier "Node" is undefined. What am I supposed to do?

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

struct Node{
    int data;
    struct Node *next;
};
struct Node* head;  //global variable head

void Insert(int x){

    struct Node* temp=(Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;  //it is the same as temp->next=NULL
    head=temp;

}

void Print(){
    struct Node* temp = head;
    printf("List is: ");
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

int main() {
    head = NULL;
    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%d",&x);
        Insert(x);
        Print();
    }

    return 0;
}

Body:
You cast the void* returned by malloc to Node*, but there is no Node type.

Here:

struct Node* temp=(Node*)malloc(sizeof(struct Node));
//                ^^^^^^^

You also do not need to cast the return from malloc. Example:

struct Node* temp = malloc(sizeof *temp);

If you'd like to use Node instead of struct Node, you can typedefine it:

typedef struct Node Node;

struct Node {
    int data;
    Node *next; // struct not needed because Node is `typedef`ined
};

You could then also do:

Node* temp = malloc(sizeof *temp);


问:
Is there a way I can print multiple lines using one print()?
I'm new to programming and having trouble understanding Python. I would like to use only one print() to lessen its usage.

first_name = "Gabh"
Gabh ="Musician"
age = 21
height = 5.4
weight = 47
print(first_name + (" is a"), Gabh)
print(("age:"), age)
print(("height:"), height)
print(("weight:"), weight)
```
<p>With this code, this is what I'm getting:</p>
<pre class="lang-py prettyprint-override"><code>Gabh is a Musician
age: 21
height: 5.4
weight: 47
</code>```

答:
Use a single print() statement, with all the items separated by commas.

```<code>print(first_name, "is a", Gabh, "age:", age, "height:", height, "weight:", weight)
</code>```

Body:
I'm new to programming and having trouble understanding Python. I would like to use only one print() to lessen its usage.

first_name = "Gabh"
Gabh ="Musician"
age = 21
height = 5.4
weight = 47
print(first_name + (" is a"), Gabh)
print(("age:"), age)
print(("height:"), height)
print(("weight:"), weight)

With this code, this is what I'm getting:

Gabh is a Musician
age: 21
height: 5.4
weight: 47

Body:
Use a single print() statement, with all the items separated by commas.

print(first_name, "is a", Gabh, "age:", age, "height:", height, "weight:", weight)


问:
C++: Inline functions and link time code generation
Up till a while a ago my code base was very close to #include hell. Every time I changed an even mildly important .h file practically all the files got recompiled.

The main reason for such high header dependency was that I have many small functions that need to be inline and I was under the impression that for inline to work they need to be in the same translation unit as the calling code, so they need to be in the header. For the inline function to even compile other headers need to be included in the header as well, ad infimum.

Enter link-time code generation (in Visual Studio). One of the main stated advantages of this is that now inline function can cross translation units.

But I'm still iffy. How can I really be sure that these functions really get inlined? I realize that the compiler can basically do whatever the hell it wants no matter where I define the function.

Is there a way to check what gets inlined?

答: I know it's taboo in C++ to say this, but you could implement the functions as preprocessor macros. Excuse me while I now go wash my mouth out with soap.</p>

OwnerDisplayName: shoosh

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: veefu


问:
How to read file from Visual Studio solution/project?
```<code> FileInfo template = new  FileInfo(@"C:\Users\bryan\Desktop\ReportTemplate.xlsx");
 template.IsReadOnly = false;
</code>```

This is fine for test, but I have the ReportTemplate.xlsx inside of my project solution. How can I use that file instead of a local one on my desktop? How do I reference the file inside the solution?

答: It depends where the file in the solution is located. The home folder is \bin\debug in the project folder which you build. If you want to reference the file which is in the root of you project folder use "..\..\yourfilename.xlsx"</p>

Body:
 FileInfo template = new  FileInfo(@"C:\Users\bryan\Desktop\ReportTemplate.xlsx");
 template.IsReadOnly = false;

This is fine for test, but I have the ReportTemplate.xlsx inside of my project solution. How can I use that file instead of a local one on my desktop? How do I reference the file inside the solution?


问:
Stripping the leading zeros but leave a single 0
So let me start of by saying that I'm new to bash so I would appreciate a simple explanation on the answers you give.

I've got the following block of code:

name="Chapter 0000 (sub s2).cbz "

s=$(echo $name | grep -Eo '[0-9]+([.][0-9]+)?' | tr '\n' ' ' | sed 's/^0*//')

echo $s

readarray -d " " -t myarr <<< "$s"

if [[ $(echo "${myarr[0]} < 100 && ${myarr[0]} >= 10" | bc) -ne 0 ]]; then
    myarr[0]="0${myarr[0]}"
elif [[ $(echo "${myarr[0]} < 10" | bc) -ne 0 ]]; then
    myarr[0]="00${myarr[0]}"
fi

newName="Chapter ${myarr[0]}.cbz"

echo $newName
```
<p>which (in this case) would end up spitting out:</p>
``` 2
(standard_in) 1: syntax error
(standard_in) 1: syntax error
Chapter .cbz
```
<p>(I'm fairly certain that the syntax errors are because <code>${myarr[0]}</code> is null when doing the comparisons)</p>
<p>This is not the output I want. I want the code to strip leading 0's but leave a single 0 if its all 0.</p>
<p>So the code to really change would be <code>sed 's/^0*//')</code> but I'm not sure how to change it.</p>
<p>(expected outputs:</p>
```              in   --->   out
1) chapter 8.cbz   ---> Chapter 008.cbz
2) chapter 1.3.cbz   ---> Chapter 001.3.cbz
3) _23 (sec 2).cbz   ---> Chapter 023.cbz
4) chapter 00009.cbz   ---> Chapter 009.cbz
5) chap 0000112.5.cbz   ---> Chapter 112.5.cbz
6) Chapter 0000 (sub s2).cbz   ---> Chapter 000.cbz
```

so far the code I got works for 1- 3 but not the leading 0 cases (4-6))

答:
In pure bash:

#!/bin/bash

for name in \
    'chapter 8.cbz' \
    'chapter 1.3.cbz' \
    '_23 (sec 2).cbz' \
    'chapter 00009.cbz' \
    'chap 0000112.5.cbz' \
    'Chapter 0000 (sub s2).cbz' \
    '_23.2 (sec 2).cbz'
do

##### The relevant part #####

[[ $name =~ ^[^0-9]*([0-9]+)([0-9.]*)[^.]*(\..*)$ ]]

chapter=$(( 10#${BASH_REMATCH[1]} ))
suffix="${BASH_REMATCH[2]}${BASH_REMATCH[3]}"

newName=$(printf 'Chapter %03d%s' "$chapter" "$suffix")

#############################

echo "$newName"

done
```
```Chapter 008.cbz
Chapter 001.3.cbz
Chapter 023.cbz
Chapter 009.cbz
Chapter 112.5.cbz
Chapter 000.cbz
Chapter 023.2.cbz
```

notes:

[[ =~ ]] is the way to use an ERE regex in bash. The one that I wrote has two capture groups: one for capturing the first appearing sequence of digits (which should be the chapter number), and one for capturing all the characters that appear after the first dot (included).

$(( 10#... )) converts a zero prefixed decimal to a normal decimal. This is needed because a number that starts with 0 would mean that's an octal instead of a decimal.

printf '%03d' converts a number to a decimal of at least 3 digits, padding the left with zeros when it's not the case.

Body:
So let me start of by saying that I'm new to bash so I would appreciate a simple explanation on the answers you give.

I've got the following block of code:

name="Chapter 0000 (sub s2).cbz "

s=$(echo $name | grep -Eo '[0-9]+([.][0-9]+)?' | tr '\n' ' ' | sed 's/^0*//')

echo $s

readarray -d " " -t myarr <<< "$s"

if [[ $(echo "${myarr[0]} < 100 && ${myarr[0]} >= 10" | bc) -ne 0 ]]; then
    myarr[0]="0${myarr[0]}"
elif [[ $(echo "${myarr[0]} < 10" | bc) -ne 0 ]]; then
    myarr[0]="00${myarr[0]}"
fi

newName="Chapter ${myarr[0]}.cbz"

echo $newName

which (in this case) would end up spitting out:

 2
(standard_in) 1: syntax error
(standard_in) 1: syntax error
Chapter .cbz

(I'm fairly certain that the syntax errors are because ${myarr[0]} is null when doing the comparisons)

This is not the output I want. I want the code to strip leading 0's but leave a single 0 if its all 0.

So the code to really change would be sed 's/^0*//') but I'm not sure how to change it.

(expected outputs:

              in   --->   out
1) chapter 8.cbz   ---> Chapter 008.cbz
2) chapter 1.3.cbz   ---> Chapter 001.3.cbz
3) _23 (sec 2).cbz   ---> Chapter 023.cbz
4) chapter 00009.cbz   ---> Chapter 009.cbz
5) chap 0000112.5.cbz   ---> Chapter 112.5.cbz
6) Chapter 0000 (sub s2).cbz   ---> Chapter 000.cbz

so far the code I got works for 1- 3 but not the leading 0 cases (4-6))

Body:
In pure bash:

#!/bin/bash

for name in \
    'chapter 8.cbz' \
    'chapter 1.3.cbz' \
    '_23 (sec 2).cbz' \
    'chapter 00009.cbz' \
    'chap 0000112.5.cbz' \
    'Chapter 0000 (sub s2).cbz' \
    '_23.2 (sec 2).cbz'
do

##### The relevant part #####

[[ $name =~ ^[^0-9]*([0-9]+)([0-9.]*)[^.]*(\..*)$ ]]

chapter=$(( 10#${BASH_REMATCH[1]} ))
suffix="${BASH_REMATCH[2]}${BASH_REMATCH[3]}"

newName=$(printf 'Chapter %03d%s' "$chapter" "$suffix")

#############################

echo "$newName"

done

Chapter 008.cbz
Chapter 001.3.cbz
Chapter 023.cbz
Chapter 009.cbz
Chapter 112.5.cbz
Chapter 000.cbz
Chapter 023.2.cbz

notes:

[[ =~ ]] is the way to use an ERE regex in bash. The one that I wrote has two capture groups: one for capturing the first appearing sequence of digits (which should be the chapter number), and one for capturing all the characters that appear after the first dot (included).

$(( 10#... )) converts a zero prefixed decimal to a normal decimal. This is needed because a number that starts with 0 would mean that's an octal instead of a decimal.

printf '%03d' converts a number to a decimal of at least 3 digits, padding the left with zeros when it's not the case.


问:
Why is my database table not loading using in ASP.NET Core
I am using a dbinitializer to try and seed data to a couple tables on my database. Everything seems to be ok except my Enrolls table doesn't want to populate. The Enrolls table holds all the List<> values of my Students and Courses. From that Enroll table I should be able to see which student is enrolled in which course. I am following a Microsoft docs tutorial but seem to hit a snag.

The thing is when I include the Enrolls property while creating an object in the initializer the entire database does not seed. However when I comment it out all tables except Enroll seed. I poked around a bit before I came here. Just hoping for a little guidance with some fresh pair of eyes as to where I should check/debug.

Truly hope I asked in a way that is understandable.

This is the DbInitializer:

```<code>public static class DbInitializer
{
    public static void Initialize(StudentRegistrationContext context)
    {
        context.Database.EnsureCreated();

        // Look for any students.
        if (context.Students.Any() )
        {
            return;   // DB has been seeded
        }

        var students = new Student[]
        {
            new Student
            {
                FirstName="A",
                LastName="B",
                Address = new Address
                            {
                              HouseNumber = "19",
                              Street="A ",
                              City="C",
                              Country = "T",
                              Email="s",
                              PhoneNumber = "6"
                               },
           **//    Enrollments = new List<Enroll> { new Enroll { CourseID = 2, ID=1 } }**
               },
            },
        };

        foreach (Student s in students)
        {
            context.Students.Add(s);
        }

        context.SaveChanges();

        var course = new Course[]
                     {
        new Course{CourseName = "Introduction to Computer Hardware",CourseCode = "ITEC120", NoOfCredits =  3, Category = Category.COMPULSORY},
        new Course{ CourseName = "Introduction to Operating Systems", CourseCode= "ITEC122", NoOfCredits = 3, Category = Category.COMPULSORY },
        new Course{ CourseName = "Programming 1",CourseCode = "ITEC133", NoOfCredits = 3, Category = Category.COMPULSORY},
        new Course{CourseName = "Human and Computer Interface Design", CourseCode = "ITEC229", NoOfCredits = 3, Category = Category.COMPULSORY},
        new Course{CourseName = "Webpage Design", CourseCode = "ITEC240", NoOfCredits = 3, Category = Category.COMPULSORY},
        new Course{CourseName = "Computer Networks Architecture and Protocol",
    };

        foreach (Course c in course)
        {
            context.Course.Add(c);
        }

        context.SaveChanges();

        var teacher = new Advisor[]
        {
            new Advisor{
                            FirstName="Teacher",
                            LastName="One",
                            Address = new Address{ HouseNumber = "123456",
                                                    Street="Teacher Street",
                                                    City="College City",
                                                    Country = "Trinidad",
                                                    Email="teacher@gmail.com",
                                                    PhoneNumber = "5648965"
                                                  },
                            Department="Department1",
                            Specialization=Category.ISD
                     },
        };

        foreach (Advisor t in teacher)
        {
            context.Advisor.Add(t);
        }
        context.SaveChanges();

        var enroll = new Enroll[]
      {
            new Enroll{CourseID = 2,  ID =2  },
      };

        foreach (Enroll e in enroll)
        {
            context.Enroll.Add(e);
        }
        context.SaveChanges();
    }
 }
</code>```

My model classes:

```<code>public class Enroll
{
    public int ID { get; set; }

    public int CourseID { get; set; }
    public Student Student { get; set; }

    public Course Course { get; set; }
   // public  DateTime RegistrationDate { get; set; }
}

public class Student : Person
{
    //  public List<Course> Attends { get; set; }
    public DateTime RegistrationDate { get; set; }
    public List<Enroll> Enrollments { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string CourseCode { get; set; }

    public double NoOfCredits { get; set; }

    public Category Category { get; set; }
    public List<Enroll> Enrollments { get; set; }
}

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public string FullName
    {
        get
        {
            return FirstName + " " + LastName;
        }
    }
}
</code>```

答:
So I figured out my issues. It was a mixture of ...

Editing the OnModelCreating function in the context

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Enroll>()
        .HasOne(s => s.Student)
        .WithMany(en => en.Enrollments)
        .HasForeignKey(fk => fk.ID);

    modelBuilder.Entity<Enroll>()
        .HasOne(s => s.Course)
        .WithMany(en => en.Enrollments)
        .HasForeignKey(fk => fk.CourseID);
}
</code>```

....and making my collection properties virtual:

```<code>public class Student : Person
{
    public DateTime RegistrationDate { get; set; }
    public  virtual List<Enroll> Enrollments { get; set; }
}

public class Enroll
{
    public int ID { get; set; }
    public int CourseID { get; set; }
    public virtual Student Student { get; set; }
    public virtual Course Course { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string CourseCode { get; set; }

    public double NoOfCredits { get; set; }

    public Category Category { get; set; }
    public virtual List<Enroll> Enrollments { get; set; }
}
</code>```

Thanks guys

Body:
I am using a dbinitializer to try and seed data to a couple tables on my database. Everything seems to be ok except my Enrolls table doesn't want to populate. The Enrolls table holds all the List<> values of my Students and Courses. From that Enroll table I should be able to see which student is enrolled in which course. I am following a Microsoft docs tutorial but seem to hit a snag.

The thing is when I include the Enrolls property while creating an object in the initializer the entire database does not seed. However when I comment it out all tables except Enroll seed. I poked around a bit before I came here. Just hoping for a little guidance with some fresh pair of eyes as to where I should check/debug.

Truly hope I asked in a way that is understandable.

This is the DbInitializer:

public static class DbInitializer
{
    public static void Initialize(StudentRegistrationContext context)
    {
        context.Database.EnsureCreated();

        // Look for any students.
        if (context.Students.Any() )
        {
            return;   // DB has been seeded
        }

        var students = new Student[]
        {
            new Student
            {
                FirstName="A",
                LastName="B",
                Address = new Address
                            {
                              HouseNumber = "19",
                              Street="A ",
                              City="C",
                              Country = "T",
                              Email="s",
                              PhoneNumber = "6"
                               },
           **//    Enrollments = new List<Enroll> { new Enroll { CourseID = 2, ID=1 } }**
               },
            },
        };

        foreach (Student s in students)
        {
            context.Students.Add(s);
        }

        context.SaveChanges();

        var course = new Course[]
                     {
        new Course{CourseName = "Introduction to Computer Hardware",CourseCode = "ITEC120", NoOfCredits =  3, Category = Category.COMPULSORY},
        new Course{ CourseName = "Introduction to Operating Systems", CourseCode= "ITEC122", NoOfCredits = 3, Category = Category.COMPULSORY },
        new Course{ CourseName = "Programming 1",CourseCode = "ITEC133", NoOfCredits = 3, Category = Category.COMPULSORY},
        new Course{CourseName = "Human and Computer Interface Design", CourseCode = "ITEC229", NoOfCredits = 3, Category = Category.COMPULSORY},
        new Course{CourseName = "Webpage Design", CourseCode = "ITEC240", NoOfCredits = 3, Category = Category.COMPULSORY},
        new Course{CourseName = "Computer Networks Architecture and Protocol",
    };

        foreach (Course c in course)
        {
            context.Course.Add(c);
        }

        context.SaveChanges();

        var teacher = new Advisor[]
        {
            new Advisor{
                            FirstName="Teacher",
                            LastName="One",
                            Address = new Address{ HouseNumber = "123456",
                                                    Street="Teacher Street",
                                                    City="College City",
                                                    Country = "Trinidad",
                                                    Email="teacher@gmail.com",
                                                    PhoneNumber = "5648965"
                                                  },
                            Department="Department1",
                            Specialization=Category.ISD
                     },
        };

        foreach (Advisor t in teacher)
        {
            context.Advisor.Add(t);
        }
        context.SaveChanges();

        var enroll = new Enroll[]
      {
            new Enroll{CourseID = 2,  ID =2  },
      };

        foreach (Enroll e in enroll)
        {
            context.Enroll.Add(e);
        }
        context.SaveChanges();
    }
 }

My model classes:

public class Enroll
{
    public int ID { get; set; }

    public int CourseID { get; set; }
    public Student Student { get; set; }

    public Course Course { get; set; }
   // public  DateTime RegistrationDate { get; set; }
}

public class Student : Person
{
    //  public List<Course> Attends { get; set; }
    public DateTime RegistrationDate { get; set; }
    public List<Enroll> Enrollments { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string CourseCode { get; set; }

    public double NoOfCredits { get; set; }

    public Category Category { get; set; }
    public List<Enroll> Enrollments { get; set; }
}

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public string FullName
    {
        get
        {
            return FirstName + " " + LastName;
        }
    }
}

Body:
So I figured out my issues. It was a mixture of ...

Editing the OnModelCreating function in the context

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Enroll>()
        .HasOne(s => s.Student)
        .WithMany(en => en.Enrollments)
        .HasForeignKey(fk => fk.ID);

    modelBuilder.Entity<Enroll>()
        .HasOne(s => s.Course)
        .WithMany(en => en.Enrollments)
        .HasForeignKey(fk => fk.CourseID);
}

....and making my collection properties virtual:

public class Student : Person
{
    public DateTime RegistrationDate { get; set; }
    public  virtual List<Enroll> Enrollments { get; set; }
}

public class Enroll
{
    public int ID { get; set; }
    public int CourseID { get; set; }
    public virtual Student Student { get; set; }
    public virtual Course Course { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string CourseCode { get; set; }

    public double NoOfCredits { get; set; }

    public Category Category { get; set; }
    public virtual List<Enroll> Enrollments { get; set; }
}

Thanks guys


问:
How to dispose or remove the overlay from a separate class?
Please help!

I have initiated the overlay from a separate class, (calling the showOverlay) now I am trying to close the same overlay by calling dispose or remove but without much success. Can anyone advise on what I am doing wrong and the best way to close the over from a separate class?

Below is a snippet of my code (its quite long)

```<code>class RootApp extends StatefulWidget {
  @override
  RootAppState createState() => RootAppState();

}

class RootAppState extends State<RootApp> {
  bool isFavorite = false;
  int pageIndex = 0;

  final FocusNode _focusNode = FocusNode();

  PageController _pgController = PageController();

  //For search
  late OverlayState? overlayState;
  late OverlayEntry overlayEntry;

  void pgCont(pg){
    print(pg);
    if(_pgController.hasClients) {
      _pgController.animateToPage(
          pg, duration: Duration(milliseconds: 250), curve: Curves.bounceInOut);
    }
    print(_pgController.hasClients);
    setState(() {

    });

  }

  @override
  Widget build(BuildContext context) {
    final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

    return Scaffold(
      extendBodyBehindAppBar: true,
      body: PageView(controller: _pgController,
          children: <Widget>[
            getMovieBody(),
            getTvBody(),
      ]),

      bottomNavigationBar: getFooter(),
    );
  }

  showOverlay(BuildContext){
    final renderBox = context.findRenderObject() as RenderBox;
    final searchOverlaySize = renderBox.size;
    overlayState = Overlay.of(context);
    overlayEntry = OverlayEntry(builder: (context)=>Positioned(
      top: 0.0,
      width: searchOverlaySize.width,
      height: searchOverlaySize.height/3,
      child: getSearchBox(),

    ),);

    overlayState?.insert(overlayEntry);
  }

  void hideOverlay() {
    print('trying to dispose');
  // overlayEntry.remove(); //LateInitializationError: Field 'overlayEntry' has not been initialized.
  //  overlayEntry.dispose(); //LateInitializationError: Field 'overlayEntry' has not been initialized.
    overlayState?.dispose(); // Error LateInitializationError: Field 'overlayState' has not been initialized.
    overlayState = null;
  }
</code>```

I'm trying to use the following to call the hideOverlay from the class searchbox..

```<code>final RootAppState roots = new RootAppState();

roots.hideOverlay();
</code>```

What Im I doing wrong or is there an easier way to call the destroy or remove the overlay? :(

答:
You should use GlobalKey to fulfill your requirement.

```<code>// define globalKey where other class have access(eg. top level scope)
GlobalKey<DemoWidgetState> globalKey = GlobalKey();

// use globelKey in RootAppState
Scaffold(
  key: globalKey
  extendBodyBehindAppBar: true,
  body: PageView(controller: _pgController, children: <Widget>[
    getMovieBody(),
    getTvBody(),
  ]),
  bottomNavigationBar: getFooter(),
);

// call hideOverlay form other class
globalKey.currentState?.hideOverlay();
</code>```

Body:
Please help!

I have initiated the overlay from a separate class, (calling the showOverlay) now I am trying to close the same overlay by calling dispose or remove but without much success. Can anyone advise on what I am doing wrong and the best way to close the over from a separate class?

Below is a snippet of my code (its quite long)

class RootApp extends StatefulWidget {
  @override
  RootAppState createState() => RootAppState();

}

class RootAppState extends State<RootApp> {
  bool isFavorite = false;
  int pageIndex = 0;

  final FocusNode _focusNode = FocusNode();

  PageController _pgController = PageController();

  //For search
  late OverlayState? overlayState;
  late OverlayEntry overlayEntry;

  void pgCont(pg){
    print(pg);
    if(_pgController.hasClients) {
      _pgController.animateToPage(
          pg, duration: Duration(milliseconds: 250), curve: Curves.bounceInOut);
    }
    print(_pgController.hasClients);
    setState(() {

    });

  }

  @override
  Widget build(BuildContext context) {
    final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

    return Scaffold(
      extendBodyBehindAppBar: true,
      body: PageView(controller: _pgController,
          children: <Widget>[
            getMovieBody(),
            getTvBody(),
      ]),

      bottomNavigationBar: getFooter(),
    );
  }

  showOverlay(BuildContext){
    final renderBox = context.findRenderObject() as RenderBox;
    final searchOverlaySize = renderBox.size;
    overlayState = Overlay.of(context);
    overlayEntry = OverlayEntry(builder: (context)=>Positioned(
      top: 0.0,
      width: searchOverlaySize.width,
      height: searchOverlaySize.height/3,
      child: getSearchBox(),

    ),);

    overlayState?.insert(overlayEntry);
  }

  void hideOverlay() {
    print('trying to dispose');
  // overlayEntry.remove(); //LateInitializationError: Field 'overlayEntry' has not been initialized.
  //  overlayEntry.dispose(); //LateInitializationError: Field 'overlayEntry' has not been initialized.
    overlayState?.dispose(); // Error LateInitializationError: Field 'overlayState' has not been initialized.
    overlayState = null;
  }

I'm trying to use the following to call the hideOverlay from the class searchbox..

final RootAppState roots = new RootAppState();

roots.hideOverlay();

What Im I doing wrong or is there an easier way to call the destroy or remove the overlay? :(

Body:
You should use GlobalKey to fulfill your requirement.

// define globalKey where other class have access(eg. top level scope)
GlobalKey<DemoWidgetState> globalKey = GlobalKey();

// use globelKey in RootAppState
Scaffold(
  key: globalKey
  extendBodyBehindAppBar: true,
  body: PageView(controller: _pgController, children: <Widget>[
    getMovieBody(),
    getTvBody(),
  ]),
  bottomNavigationBar: getFooter(),
);

// call hideOverlay form other class
globalKey.currentState?.hideOverlay();


问:
Static Hangfire RecurringJob methods in LINQPad are not behaving
I have a script in LINQPad that looks like this:

```<code>var serverMode = EnvironmentType.EWPROD;
var jobToSchedule = JobType.ABC;
var hangfireCs = GetConnectionString(serverMode);
JobStorage.Current = new SqlServerStorage(hangfireCs);

Action<string, string, XElement> createOrReplaceJob =
    (jobName, cronExpression, inputPackage) =>
    {
        RecurringJob.RemoveIfExists(jobName);
        RecurringJob.AddOrUpdate(
            jobName,
             () => new BTR.Evolution.Hangfire.Schedulers.JobInvoker().Invoke(
                     jobName,
                     inputPackage,
                     null,
                     JobCancellationToken.Null),
            cronExpression, TimeZoneInfo.Local);
    };

// psuedo code to prepare inputPackage for client ABC...

createOrReplaceJob("ABC.CustomReport.SurveyResults", "0 2 * * *", inputPackage);

JobStorage.Current.GetConnection().GetRecurringJobs().Where( j => j.Id.StartsWith( jobToSchedule.ToString() ) ).Dump( "Scheduled Jobs" );
</code>```

I have to schedule in both QA and PROD.  To do that, I toggle the serverMode variable and run it once for EWPROD and once for EWQA.  This all worked fine until recently, and I don't know exactly when it changed unfortunately because I don't always have to run in both environments.

I did purchase/install LINQPad 7 two days ago to look at some C# 10 features and I'm not sure if that affected it.

But here is the problem/flow:

Run it for EWQA and everything works.

Run it for EWPROD and the script (Hangfire components) seem to run in a mix of QA and PROD.

When I'm running it the 'second time' in EWPROD I've confirmed:

The hangfireCs (connection string) is right (pointing to PROD) and it is assigned to JobStorage.Current

The query at the end of the script, JobStorage.Current.GetConnection().GetRecurringJobs() uses the right connection.

The RecurringJob.* methods inside the createOrReplaceJob Action use the connection from the previous run (i.e. EWQA).  If I monitor my QA Hangfire db, I see the job removed and added.

Temporary workaround:

Run it for EWQA and everything works.

Restart LINQPad or use 'Cancel and Reset All Queries' method

Run it for EWPROD and now everything works.

So I'm at a loss of where the issue might lie.  I feel like my upgrade/install of LINQPad7 might be causing problems, but I'm not sure if there is a different way to make the RecurringJob.* static methods use the 'updated' connection string.

Any ideas on why the restart or reset is now needed?

LINQPad - 5.44.02
Hangfire.Core - 1.7.17
Hangfire.SqlServer - 1.7.17

答:
This is caused by your script (or a library that you call) caching something statically, and not cleaning up between executions.

Either clear/dispose objects when you're done (e.g., JobStorage.Current?) or tell LINQPad not to re-use the process between executions, by adding Util.NewProcess=true; to your script.

Body:
I have a script in LINQPad that looks like this:

var serverMode = EnvironmentType.EWPROD;
var jobToSchedule = JobType.ABC;
var hangfireCs = GetConnectionString(serverMode);
JobStorage.Current = new SqlServerStorage(hangfireCs);

Action<string, string, XElement> createOrReplaceJob =
    (jobName, cronExpression, inputPackage) =>
    {
        RecurringJob.RemoveIfExists(jobName);
        RecurringJob.AddOrUpdate(
            jobName,
             () => new BTR.Evolution.Hangfire.Schedulers.JobInvoker().Invoke(
                     jobName,
                     inputPackage,
                     null,
                     JobCancellationToken.Null),
            cronExpression, TimeZoneInfo.Local);
    };

// psuedo code to prepare inputPackage for client ABC...

createOrReplaceJob("ABC.CustomReport.SurveyResults", "0 2 * * *", inputPackage);

JobStorage.Current.GetConnection().GetRecurringJobs().Where( j => j.Id.StartsWith( jobToSchedule.ToString() ) ).Dump( "Scheduled Jobs" );

I have to schedule in both QA and PROD.  To do that, I toggle the serverMode variable and run it once for EWPROD and once for EWQA.  This all worked fine until recently, and I don't know exactly when it changed unfortunately because I don't always have to run in both environments.

I did purchase/install LINQPad 7 two days ago to look at some C# 10 features and I'm not sure if that affected it.

But here is the problem/flow:

Run it for EWQA and everything works.

Run it for EWPROD and the script (Hangfire components) seem to run in a mix of QA and PROD.

When I'm running it the 'second time' in EWPROD I've confirmed:

The hangfireCs (connection string) is right (pointing to PROD) and it is assigned to JobStorage.Current

The query at the end of the script, JobStorage.Current.GetConnection().GetRecurringJobs() uses the right connection.

The RecurringJob.* methods inside the createOrReplaceJob Action use the connection from the previous run (i.e. EWQA).  If I monitor my QA Hangfire db, I see the job removed and added.

Temporary workaround:

Run it for EWQA and everything works.

Restart LINQPad or use 'Cancel and Reset All Queries' method

Run it for EWPROD and now everything works.

So I'm at a loss of where the issue might lie.  I feel like my upgrade/install of LINQPad7 might be causing problems, but I'm not sure if there is a different way to make the RecurringJob.* static methods use the 'updated' connection string.

Any ideas on why the restart or reset is now needed?

LINQPad - 5.44.02
Hangfire.Core - 1.7.17
Hangfire.SqlServer - 1.7.17


问:
uploading images in winforms application
Does anyone know if a there is a control to allow the user to upload a image to a windows form?  Or any example code to accomplish this.

I am using win-form applications

Thanks,

答:
To allow users to select files in a Windows Forms application you should look into using the OpenFileDialog class.

To use the dialog on your form you will need to find it in the toolbox in Visual Studio and drag it on to your form.

Once associated with the form you can then invoke the dialog from your code like so:

```<code>if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string selectedFile = openFileDialog1.FileName;
}
</code>```

You can then use the file path to perform whatever task you wish with the file.

Note: You can use the FileDialog.Filter Property to limit the type of file extensions (images in your case) the user can select when using the dialog.

Body:
To allow users to select files in a Windows Forms application you should look into using the OpenFileDialog class.

To use the dialog on your form you will need to find it in the toolbox in Visual Studio and drag it on to your form.

Once associated with the form you can then invoke the dialog from your code like so:

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string selectedFile = openFileDialog1.FileName;
}

You can then use the file path to perform whatever task you wish with the file.

Note: You can use the FileDialog.Filter Property to limit the type of file extensions (images in your case) the user can select when using the dialog.


问:
Docker Network for containers from different docker compose
I'm developing microservices based on node JS/Express with multiple containers. Different group of containers deployed with different docker compose. Eg. One docker compose contains 4 docker containers, while other docker compose contains 3 docker containers.
Docker compose created automatic network for each docker compose, eg. BackendA_default and BackendB_default, thus each backend cannot talk to each other as they're on separate network. Even if I specify the network to eg. backend, it will still show BackendA_backend instead of just 'backend' network. I already tried using 'bridge' and 'host' network, it still doesn't work.

How do I make this 2 groups of docker network connect to each other ?

答:
Create your networks outside of docker-compose using docker network create:

```<code>docker network create my-app-network
</code>```

And then use them in your compose files as an "external" network:

```<code>version: 3

services:
  database:
    image: docker.io/postgres
    network: my-app-network

networks:
  default:
    external: true
    name: my-app-network
</code>```

This will allow you to attach containers from multiple compose stacks to the same network.

Body:
Create your networks outside of docker-compose using docker network create:

docker network create my-app-network

And then use them in your compose files as an "external" network:

version: 3

services:
  database:
    image: docker.io/postgres
    network: my-app-network

networks:
  default:
    external: true
    name: my-app-network

This will allow you to attach containers from multiple compose stacks to the same network.