问:
How to get exact scroll position when animating elements onScroll
I am trying to animate elements while scrolling based on the elements progress through the scene. I am running into the issue of the browser returning intermittent scroll positions making it difficult to be exact when starting and stopping element animation.

Minimal example:

Fiddle Fiddle Demo

const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();

let yScroll = window.scrollY;
let yCurrent = yScroll;
let AF = null;

const start = triggerRect.top - yScroll - 200;
const end = start + 400;

const updateScroll = () => {
 yScroll = window.scrollY;
  startAnimation();
}

const startAnimation = () => {
  if(!AF) AF = requestAnimationFrame(animate)
}

const cancelAnimation = () => {
  yCurrent = yScroll;
  cancelAnimationFrame(AF);
  AF = null;
}

const animate = () => {
  if(yCurrent === yScroll) cancelAnimation();
  else {
   updateElements();
    yCurrent = yScroll;
    AF = requestAnimationFrame(animate);
  }
}

const updateElements = () => {
  const pos = yCurrent - start;
  if(inScene()){
    tweens[0].style.transform = `translateX(${pos}px)`;
    tweens[1].style.transform = `translateY(${pos}px)`;
  }
}

const inScene = () => {
  return start <= yCurrent && end >= yCurrent ? true : false;
};

window.addEventListener('scroll', updateScroll);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
  position:relative;
  margin: 100vh 20px;
  background: rgb(240,240,240);
  height: 900px;
  border: 1px solid red;
}

.line{
  position:absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: red;
}

.start{
  top: 200px;
}

.end{
  bottom: 200px;
}

.tween{
  position:absolute;
  top:200px;
  width: 100px;
  height: 100px;
  background: blue;
}

.left{
  left: 0;
}

.right{
  right: 0;
}</code>```

Scroll Down

```

As you can see the elements are supposed to stop on the lines but when you scroll they never really do.  And the faster you scroll the worse it becomes.

So is there a technique to either return the correct scroll position or somehow debounce the elements so then can reach the full range when scrolling instead of constantly coming up short of their intended position?

I know this is possible because scrolling libraries like ScrollMagic do a pretty good job of handling this but I don't really want to deconstruct then entire ScrollMagic framework to find out how they achieve it.  I would use the ScrollMagic framework itself but I am trying to have a momentum style scrolling container wrapping the page and translating it on scroll along with elements inside this container and using ScrollMagic it is pretty buggy.  So I figured I would post the question here and see if anyone had any experience or insight on the situation.

Any guidance would be appreciated as I have been mulling over this for a while.

答:
Let's assume that browser is what it is and not all pixels travelled by will result in an event. You end up with elements away from the end because you check for the scroll position if it's "in scene". When it's 5x before - it's fine. Next thing it is 5px after - you ignore it. What you can do is to animate objects to their final positions whenever you scroll outside the scene instead of ignoring it.

So just to start it, I would change this:

const updateElements = () => {
  let pos = yCurrent - start;
  pos = Math.min(400, Math.max(0, pos));
  tweens[0].style.transform = `translateX(${pos}px)`;
  tweens[1].style.transform = `translateY(${pos}px)`;
}
```

<p>It can be optimised more so it will start animation only once when it's outside the "scene". Let me know if you have problem with that as well.</p>

<p><strong>UPDATE:</strong></p>

<p>Here's the version that animates only if needed:</p>

<pre class="lang-js prettyprint-override"><code>const updateElements = () => {
  let pos = yCurrent - start;
  pos = Math.min(400, Math.max(0, pos));
  const styles = [...tweens].map(tween => window.getComputedStyle(tween, null));
  const transforms = styles.map(style => new WebKitCSSMatrix(style.getPropertyValue('transform')));
  if (transforms[0].m41 !== pos) {
    tweens[0].style.transform = `translateX(${pos}px)`;
  }

  if (transforms[1].m42 !== pos) {
    tweens[1].style.transform = `translateY(${pos}px)`;
  }
}
</code>```

Reading translate is hell, so if we care only about Webkit browsers we can use WebKitCSSMatrix, but Firefox doesn't have anything like that so you can use something external

And I agree with artanik it does work better without requestAnimationFrame

Body:
I am trying to animate elements while scrolling based on the elements progress through the scene. I am running into the issue of the browser returning intermittent scroll positions making it difficult to be exact when starting and stopping element animation.

Minimal example:

Fiddle Fiddle Demo

const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();

let yScroll = window.scrollY;
let yCurrent = yScroll;
let AF = null;

const start = triggerRect.top - yScroll - 200;
const end = start + 400;

const updateScroll = () => {
 yScroll = window.scrollY;
  startAnimation();
}

const startAnimation = () => {
  if(!AF) AF = requestAnimationFrame(animate)
}

const cancelAnimation = () => {
  yCurrent = yScroll;
  cancelAnimationFrame(AF);
  AF = null;
}

const animate = () => {
  if(yCurrent === yScroll) cancelAnimation();
  else {
   updateElements();
    yCurrent = yScroll;
    AF = requestAnimationFrame(animate);
  }
}

const updateElements = () => {
  const pos = yCurrent - start;
  if(inScene()){
    tweens[0].style.transform = `translateX(${pos}px)`;
    tweens[1].style.transform = `translateY(${pos}px)`;
  }
}

const inScene = () => {
  return start <= yCurrent && end >= yCurrent ? true : false;
};

window.addEventListener('scroll', updateScroll);

.wrapper{
  position:relative;
  margin: 100vh 20px;
  background: rgb(240,240,240);
  height: 900px;
  border: 1px solid red;
}

.line{
  position:absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: red;
}

.start{
  top: 200px;
}

.end{
  bottom: 200px;
}

.tween{
  position:absolute;
  top:200px;
  width: 100px;
  height: 100px;
  background: blue;
}

.left{
  left: 0;
}

.right{
  right: 0;
}

Scroll Down

As you can see the elements are supposed to stop on the lines but when you scroll they never really do.  And the faster you scroll the worse it becomes.

So is there a technique to either return the correct scroll position or somehow debounce the elements so then can reach the full range when scrolling instead of constantly coming up short of their intended position?

I know this is possible because scrolling libraries like ScrollMagic do a pretty good job of handling this but I don't really want to deconstruct then entire ScrollMagic framework to find out how they achieve it.  I would use the ScrollMagic framework itself but I am trying to have a momentum style scrolling container wrapping the page and translating it on scroll along with elements inside this container and using ScrollMagic it is pretty buggy.  So I figured I would post the question here and see if anyone had any experience or insight on the situation.

Any guidance would be appreciated as I have been mulling over this for a while.

Body:
Let's assume that browser is what it is and not all pixels travelled by will result in an event. You end up with elements away from the end because you check for the scroll position if it's "in scene". When it's 5x before - it's fine. Next thing it is 5px after - you ignore it. What you can do is to animate objects to their final positions whenever you scroll outside the scene instead of ignoring it.

So just to start it, I would change this:

const updateElements = () => {
  let pos = yCurrent - start;
  pos = Math.min(400, Math.max(0, pos));
  tweens[0].style.transform = `translateX(${pos}px)`;
  tweens[1].style.transform = `translateY(${pos}px)`;
}

It can be optimised more so it will start animation only once when it's outside the "scene". Let me know if you have problem with that as well.

UPDATE:

Here's the version that animates only if needed:

const updateElements = () => {
  let pos = yCurrent - start;
  pos = Math.min(400, Math.max(0, pos));
  const styles = [...tweens].map(tween => window.getComputedStyle(tween, null));
  const transforms = styles.map(style => new WebKitCSSMatrix(style.getPropertyValue('transform')));
  if (transforms[0].m41 !== pos) {
    tweens[0].style.transform = `translateX(${pos}px)`;
  }

  if (transforms[1].m42 !== pos) {
    tweens[1].style.transform = `translateY(${pos}px)`;
  }
}

Reading translate is hell, so if we care only about Webkit browsers we can use WebKitCSSMatrix, but Firefox doesn't have anything like that so you can use something external

And I agree with artanik it does work better without requestAnimationFrame


来源: stackexchange

答:
The problem is down to inScene() becoming false and you aren't setting the final animation position to the minimum / maximum position. It was also jerking because yScroll value doesn't update until animation starts and that is too late.

```<code>const updateElements = () => {
  yScroll = window.scrollY;
  var pos = yScroll - start;

  if (pos < 0) {
    pos = 0;
  }
  else if (pos > end - start) {
    pos = end - start;
  }

  //if (inScene()){
    tweens[0].style.transform = `translateX(${pos}px)`;
    tweens[1].style.transform = `translateY(${pos}px)`;
  //}
}
</code>```

All this works now see jsfiddle: https://jsfiddle.net/nLh748y3/1/

I've commented out the inScene() for now. If you want this back in then work backward from  this working version until you get what you want to achieve.

ContentLicense: CC BY-SA 4.0

Title: How to get exact scroll position when animating elements onScroll

Body:
The problem is down to inScene() becoming false and you aren't setting the final animation position to the minimum / maximum position. It was also jerking because yScroll value doesn't update until animation starts and that is too late.

const updateElements = () => {
  yScroll = window.scrollY;
  var pos = yScroll - start;

  if (pos < 0) {
    pos = 0;
  }
  else if (pos > end - start) {
    pos = end - start;
  }

  //if (inScene()){
    tweens[0].style.transform = `translateX(${pos}px)`;
    tweens[1].style.transform = `translateY(${pos}px)`;
  //}
}

All this works now see jsfiddle: https://jsfiddle.net/nLh748y3/1/

I've commented out the inScene() for now. If you want this back in then work backward from  this working version until you get what you want to achieve.


问:
Remove numbers if greater than X - PHP
I am removing numbers from $name, as follows:

```<code>$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
</code>```

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

答:
I think thats it:</p>

```<code>preg_match_all('!\d+!', $namewithoutnumber, $matches);
$numbers = implode('', $matches[0]);

if( strlen($numbers) > 5 ) {
  $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
}
</code>```

Title: Remove numbers if greater than X - PHP

Body:
I am removing numbers from $name, as follows:

$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

Body:
I think thats it:

preg_match_all('!\d+!', $namewithoutnumber, $matches);
$numbers = implode('', $matches[0]);

if( strlen($numbers) > 5 ) {
  $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
}


问:
python function to return a tuple of filenames without extensions and dictionary where file extensions are keys and file names are values
I am trying to write a function in python, which will get a filename as a parameter. The file contains filenames with and without extensions. The function will make a dictionary with extensions as keys and list of filenames with that particular extension as values. At the end, function will return a tuple where first part of that tuple is a list of filenames without extensions and the other part is dictionary described above. The code I have written is pasted below:

```<code>import re
def file_extensions(filename):
    with open(filenames, 'r') as f:
        lines = f.read()
        ext = re.findall(r'\w+\.?\w+\.{1}(\w+)', lines)
        f.seek(0)
        lines_dict = f.readlines()
        d = {k:[v] for k, v in zip(ext, lines_dict)}
    return ([filenames without extensionts], d)
</code>```

The contents of the input file are:

```<code>file1.txt
mydocument.pdf
file2.txt
archive.tar.gz
test
</code>```

The function should return:

```<code>(["test"], { "txt" : ["file1.txt", "file2.txt"], "pdf" : ["mydocument.pdf"], "gz" : ["archive.tar.gz"] } )
</code>```

However, my function is not complete, I am first struggling with the dictionary and then to make the list of file names without extensions.

EDIT:
I have been able to write the function now,below is my code:

```<code>def file_extensions(filename):
    with_ext = []
    ext = []
    no_ext = []
    with open(filename, 'r') as f:
        for line in f:
            res = line.rstrip().rsplit('.',maxsplit=1)
            if len(res) == 1:
                no_ext.append(res[0])
            else:
                fulna = '.'.join(res)
                ext.append(res[1])
                with_ext.append(fulna)
        dicta = {k:[v] for k, v in zip(ext, with_ext)}
    return (no_ext, dicta)
print(file_extensions('filenames.txt'))
</code>```

It prints:

```<code>(['test'], {'txt': ['file2.txt'], 'pdf': ['mydocument.pdf'], 'gz': ['archive.tar.gz']})
</code>```

There is one thing it does not do. Which is, in the dictionary, it should append all the filenames with the same extension as values infront of the extension. Comparing below the original output vs expected output:

```<code>Original output of my code:
(['test'], {'txt': ['file2.txt'], 'pdf': ['mydocument.pdf'], 'gz': ['archive.tar.gz']})

Expected output:
(["test"], { "txt" : ["file1.txt", "file2.txt"], "pdf" : ["mydocument.pdf"], "gz" : ["archive.tar.gz"] } )
</code>```

答:
You don't need a regex for this, you could just iterate and split the filename with rsplit and append to the dict or list according to the size of the result.</p>

```<code>>>> with_ext = defaultdict(list)
>>> no_ext = []
>>> with open('example.txt', 'r') as f:
...     for line in f:
...             res = line.rstrip().rsplit('.',maxsplit=1)
...             if len(res) == 1:
...                     no_ext.append(res[0])
...             else:
...                     with_ext[res[1]].append(res[0])
...
>>> no_ext
['test']
>>> with_ext
defaultdict(<class 'list'>, {'txt': ['file1', 'file2'], 'pdf': ['mydocument'], 'gz': ['archive.tar']})
</code>```

Body:
I am trying to write a function in python, which will get a filename as a parameter. The file contains filenames with and without extensions. The function will make a dictionary with extensions as keys and list of filenames with that particular extension as values. At the end, function will return a tuple where first part of that tuple is a list of filenames without extensions and the other part is dictionary described above. The code I have written is pasted below:

import re
def file_extensions(filename):
    with open(filenames, 'r') as f:
        lines = f.read()
        ext = re.findall(r'\w+\.?\w+\.{1}(\w+)', lines)
        f.seek(0)
        lines_dict = f.readlines()
        d = {k:[v] for k, v in zip(ext, lines_dict)}
    return ([filenames without extensionts], d)

The contents of the input file are:

file1.txt
mydocument.pdf
file2.txt
archive.tar.gz
test

The function should return:

(["test"], { "txt" : ["file1.txt", "file2.txt"], "pdf" : ["mydocument.pdf"], "gz" : ["archive.tar.gz"] } )

However, my function is not complete, I am first struggling with the dictionary and then to make the list of file names without extensions.

EDIT:
I have been able to write the function now,below is my code:

def file_extensions(filename):
    with_ext = []
    ext = []
    no_ext = []
    with open(filename, 'r') as f:
        for line in f:
            res = line.rstrip().rsplit('.',maxsplit=1)
            if len(res) == 1:
                no_ext.append(res[0])
            else:
                fulna = '.'.join(res)
                ext.append(res[1])
                with_ext.append(fulna)
        dicta = {k:[v] for k, v in zip(ext, with_ext)}
    return (no_ext, dicta)
print(file_extensions('filenames.txt'))

It prints:

(['test'], {'txt': ['file2.txt'], 'pdf': ['mydocument.pdf'], 'gz': ['archive.tar.gz']})

There is one thing it does not do. Which is, in the dictionary, it should append all the filenames with the same extension as values infront of the extension. Comparing below the original output vs expected output:

Original output of my code:
(['test'], {'txt': ['file2.txt'], 'pdf': ['mydocument.pdf'], 'gz': ['archive.tar.gz']})

Expected output:
(["test"], { "txt" : ["file1.txt", "file2.txt"], "pdf" : ["mydocument.pdf"], "gz" : ["archive.tar.gz"] } )

Body:
You don't need a regex for this, you could just iterate and split the filename with rsplit and append to the dict or list according to the size of the result.

>>> with_ext = defaultdict(list)
>>> no_ext = []
>>> with open('example.txt', 'r') as f:
...     for line in f:
...             res = line.rstrip().rsplit('.',maxsplit=1)
...             if len(res) == 1:
...                     no_ext.append(res[0])
...             else:
...                     with_ext[res[1]].append(res[0])
...
>>> no_ext
['test']
>>> with_ext
defaultdict(<class 'list'>, {'txt': ['file1', 'file2'], 'pdf': ['mydocument'], 'gz': ['archive.tar']})


问:
How do I print a hex number representing a IEEE 754 float as a float in ruby
I am using ruby to parse a datastream, some parts of which are IEEE-754 floats, but am not sure how to print these as floats. For example:

```<code>f = 0xbe80fd31 # -0.2519317
puts "%f" % f
3196124465.000000
</code>```

how do I get -0.2519317 ?

答:
Any time your converting a binary byte stream to something else, you usually end up using String#unpack (and Array#pack if you're going the other way).

If you have these bytes:

```<code>bytes = [0xbe, 0x80, 0xfd, 0x31]
</code>```

then you could say:

```<code>bytes.map(&:chr).join.unpack('g')
# [-0.25193169713020325]
</code>```

and then unwrap the array. This:

```<code>bytes.map(&:chr).join
</code>```

packs the bytes into the string:

```<code>"\xbe\x80\xfd\x31"
</code>```

which is suitable for #unpack. You could also (thanks Stefan) say:

```<code># Variations on getting the bytes into a string for `#unpack`
bytes.pack('C4').unpack('g').first
[0xbe80fd31].pack('L>').unpack('g').first

# Variations using `#unpack1`
bytes.map(&:chr).join.unpack1('g')
bytes.pack('C4').unpack1('g')
[0xbe80fd31].pack('L>').unpack1('g')
</code>```

If you already have the string then you go can straight to #unpack or #unpack1.

You'll want to use 'e' instead of 'g' your bytes are in a different order and 'E' or 'G' if you actually have an eight byte double rather than a four byte float.

Body:
I am using ruby to parse a datastream, some parts of which are IEEE-754 floats, but am not sure how to print these as floats. For example:

f = 0xbe80fd31 # -0.2519317
puts "%f" % f
3196124465.000000

how do I get -0.2519317 ?

Body:
Any time your converting a binary byte stream to something else, you usually end up using String#unpack (and Array#pack if you're going the other way).

If you have these bytes:

bytes = [0xbe, 0x80, 0xfd, 0x31]

then you could say:

bytes.map(&:chr).join.unpack('g')
# [-0.25193169713020325]

and then unwrap the array. This:

bytes.map(&:chr).join

packs the bytes into the string:

"\xbe\x80\xfd\x31"

which is suitable for #unpack. You could also (thanks Stefan) say:

# Variations on getting the bytes into a string for `#unpack`
bytes.pack('C4').unpack('g').first
[0xbe80fd31].pack('L>').unpack('g').first

# Variations using `#unpack1`
bytes.map(&:chr).join.unpack1('g')
bytes.pack('C4').unpack1('g')
[0xbe80fd31].pack('L>').unpack1('g')

If you already have the string then you go can straight to #unpack or #unpack1.

You'll want to use 'e' instead of 'g' your bytes are in a different order and 'E' or 'G' if you actually have an eight byte double rather than a four byte float.


问:
Timer implementation for rpc method
I have a Go RPC server that serves client requests. A client requests work (or task) from the server and the server assigns a task to the client. The server expects workers (or clients) to finish any task within a time limit. Therefore a timeout event callback mechanism is required on the server-side.

Here is what I tried so far.

```<code>func (l *Listener) RequestHandler(request string, reply string) error {
    // some other work
    // ....
    _timer := time.NewTimer(time.Second * 5) // timer for 2 seconds
    go func() {
        // simulates a client not replying case, with timeout of 2 sec
        y := <-_timer.C
        fmt.Println("TimeOut for client")
        // revert state changes becasue of client fail
    }()

    // set reply
    // update some states
    return nil
}
</code>```

In the above snippet for each request from a worker (or a client) the handler in the server-side starts a timer and a goroutine. The goroutine reverts the changes done by the handler function before sending a reply to the client.

Is there any way of creating a "set of timers" and blocking wait on the "set of timers" ? Further, whenever a timer expires the blocking wait wakes up and provides us with the timer handles. Depending on the timer type we can perform different expiry handler functions in the runtime.

I am trying to implement a similar mechanism in Go that we can implement in C++ with timerfd with epoll.

Full code for the sample implementation of timers in Go. server.go and client.go.

答:
I suggest you to explored the context package

it can be be done like this:

```<code>func main() {
    c := context.Background()
    wg := &sync.WaitGroup{}
    f(c, wg)
    wg.Wait()
}

func f(c context.Context, wg *sync.WaitGroup) {
    c, _ = context.WithTimeout(c, 3*time.Second)
    wg.Add(1)

    go func(c context.Context) {
        defer wg.Done()
        select {
        case <-c.Done():
            fmt.Println("f() Done:", c.Err())
            return
        case r := <-time.After(5 * time.Second):
            fmt.Println("f():", r)
        }
    }(c)
}
</code>```

basically you initiate a base context and then derive other contexts from it, when a context is terminated, either by passing the time or a call to its close, it closes its Done channel and the Done channel of all the contexts that are derived from it.

Title: Timer implementation for rpc method

Body:
I have a Go RPC server that serves client requests. A client requests work (or task) from the server and the server assigns a task to the client. The server expects workers (or clients) to finish any task within a time limit. Therefore a timeout event callback mechanism is required on the server-side.

Here is what I tried so far.

func (l *Listener) RequestHandler(request string, reply string) error {
    // some other work
    // ....
    _timer := time.NewTimer(time.Second * 5) // timer for 2 seconds
    go func() {
        // simulates a client not replying case, with timeout of 2 sec
        y := <-_timer.C
        fmt.Println("TimeOut for client")
        // revert state changes becasue of client fail
    }()

    // set reply
    // update some states
    return nil
}

In the above snippet for each request from a worker (or a client) the handler in the server-side starts a timer and a goroutine. The goroutine reverts the changes done by the handler function before sending a reply to the client.

Is there any way of creating a "set of timers" and blocking wait on the "set of timers" ? Further, whenever a timer expires the blocking wait wakes up and provides us with the timer handles. Depending on the timer type we can perform different expiry handler functions in the runtime.

I am trying to implement a similar mechanism in Go that we can implement in C++ with timerfd with epoll.

Full code for the sample implementation of timers in Go. server.go and client.go.

Body:
I suggest you to explored the context package

it can be be done like this:

func main() {
    c := context.Background()
    wg := &sync.WaitGroup{}
    f(c, wg)
    wg.Wait()
}

func f(c context.Context, wg *sync.WaitGroup) {
    c, _ = context.WithTimeout(c, 3*time.Second)
    wg.Add(1)

    go func(c context.Context) {
        defer wg.Done()
        select {
        case <-c.Done():
            fmt.Println("f() Done:", c.Err())
            return
        case r := <-time.After(5 * time.Second):
            fmt.Println("f():", r)
        }
    }(c)
}

basically you initiate a base context and then derive other contexts from it, when a context is terminated, either by passing the time or a call to its close, it closes its Done channel and the Done channel of all the contexts that are derived from it.


问:
How can I troubleshoot: A connection was successfully established with the server, but then an error occurred during the login process
I am trying to create the application in this demo but with my own database. All I am trying to do for now, is show one data table. I am using Visual studio 2017 pro, and am connecting to an older SQL Server version 10.50.1600. I am able to connect to the database with windows authentication via SSMS, but when I try to connect with my application I get the following error message.

A connection was successfully established with the server, but then an
  error occurred during the login process. (provider: TCP Provider,
  error: 0 - The operation completed successfully)

I have the following capabilities enabled: Enterprise Authentication, Internet (Client & Server), Internet(Client), Private Networks(Client & Server)

I changed the server to another, more current DB server, and it worked... so I am thinking it may be a setting on the database server that I have to change. I have no idea how to know what to change though.

I am running under UWP build 16299, and have followed the steps in the demo very closely. I've re-created this app a few times to ensure that I am not missing any steps. The rest of the app works fine.

I have spent hours looking around the internet for a solution for this error. There seem to be many reasons that this error can come up but I have yet to see a solution that worked for me.

I'm wondering if people can give me tips on where I can look to see why this is happening. I can't see anything helpful in the Autos list, but I'll attach it in case there's something that jumps out at others.

My connection string and class are below. As I mentioned, it does connect, but then complains about something at login:

Screenshot of error message

Connection String

```<code>public string ConnectionString { get; set; } = "Server=servername; Trusted_Connection=Yes; Integrated Security=True;";
</code>```

Connection Class

```<code>public ObservableCollection<MyAssignments> GetMyAssignments(string connectionString)
        {
            string GetMyAssignmentsSQLFile = File.ReadAllText(@".\SQL\MyOpenAssignments.sql");

            var myAssignments = new ObservableCollection<MyAssignments>();
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {

                    conn.Open();
                    if (conn.State == System.Data.ConnectionState.Open)
                    {
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = GetMyAssignmentsSQLFile;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var myAssignment = new MyAssignments();

                                    myAssignment.CallID = reader.GetString(0);
                                    myAssignment.RecvdDate = reader.GetString(1);
                                    myAssignment.CallStatus = reader.GetString(2);
                                    myAssignment.Priority = reader.GetString(3);
                                    myAssignment.Classification = reader.GetString(4);
                                    myAssignment.CallDesc = reader.GetString(5);
                                    myAssignment.CloseDesc = reader.GetString(6);
                                    myAssignments.Add(myAssignment);
                                }
                            }
                        }
                    }
                }
                return myAssignments;
            }
            catch (Exception eSql)
            {
                Debug.WriteLine("SQL-Exception: " + eSql.Message);
            }
            return null;
        }
    }
</code>```

答:
Ensure that the database name is correct. I had the problem (same error message) and all I did to fix it is fix the database name.

I do not see a database name in the connection string but I might not know how it is properly specified. For the future though, check the database name.

Body:
I am trying to create the application in this demo but with my own database. All I am trying to do for now, is show one data table. I am using Visual studio 2017 pro, and am connecting to an older SQL Server version 10.50.1600. I am able to connect to the database with windows authentication via SSMS, but when I try to connect with my application I get the following error message.

A connection was successfully established with the server, but then an
  error occurred during the login process. (provider: TCP Provider,
  error: 0 - The operation completed successfully)

I have the following capabilities enabled: Enterprise Authentication, Internet (Client & Server), Internet(Client), Private Networks(Client & Server)

I changed the server to another, more current DB server, and it worked... so I am thinking it may be a setting on the database server that I have to change. I have no idea how to know what to change though.

I am running under UWP build 16299, and have followed the steps in the demo very closely. I've re-created this app a few times to ensure that I am not missing any steps. The rest of the app works fine.

I have spent hours looking around the internet for a solution for this error. There seem to be many reasons that this error can come up but I have yet to see a solution that worked for me.

I'm wondering if people can give me tips on where I can look to see why this is happening. I can't see anything helpful in the Autos list, but I'll attach it in case there's something that jumps out at others.

My connection string and class are below. As I mentioned, it does connect, but then complains about something at login:

Screenshot of error message

Connection String

public string ConnectionString { get; set; } = "Server=servername; Trusted_Connection=Yes; Integrated Security=True;";

Connection Class

public ObservableCollection<MyAssignments> GetMyAssignments(string connectionString)
        {
            string GetMyAssignmentsSQLFile = File.ReadAllText(@".\SQL\MyOpenAssignments.sql");

            var myAssignments = new ObservableCollection<MyAssignments>();
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {

                    conn.Open();
                    if (conn.State == System.Data.ConnectionState.Open)
                    {
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = GetMyAssignmentsSQLFile;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var myAssignment = new MyAssignments();

                                    myAssignment.CallID = reader.GetString(0);
                                    myAssignment.RecvdDate = reader.GetString(1);
                                    myAssignment.CallStatus = reader.GetString(2);
                                    myAssignment.Priority = reader.GetString(3);
                                    myAssignment.Classification = reader.GetString(4);
                                    myAssignment.CallDesc = reader.GetString(5);
                                    myAssignment.CloseDesc = reader.GetString(6);
                                    myAssignments.Add(myAssignment);
                                }
                            }
                        }
                    }
                }
                return myAssignments;
            }
            catch (Exception eSql)
            {
                Debug.WriteLine("SQL-Exception: " + eSql.Message);
            }
            return null;
        }
    }


答:
You can use preg_replace to remove all the digits from the name, and if the length of the new name is 6 or more less than the old name, replace the old name:

```<code>$names = array('joe123456',
               'joe123',
               '1joe1234',
               '123joe456');

foreach ($names as $name) {
    $new_name = preg_replace('/\d/', '', $name);
    if (strlen($new_name) <= strlen($name) - 6) {
        $name = $new_name;
    }
    echo "$name\n";
}
</code>```

Output:

```<code>joe
joe123
1joe1234
joe
</code>```

Demo on 3v4l.org

Title: Remove numbers if greater than X - PHP

Body:
You can use preg_replace to remove all the digits from the name, and if the length of the new name is 6 or more less than the old name, replace the old name:

$names = array('joe123456',
               'joe123',
               '1joe1234',
               '123joe456');

foreach ($names as $name) {
    $new_name = preg_replace('/\d/', '', $name);
    if (strlen($new_name) <= strlen($name) - 6) {
        $name = $new_name;
    }
    echo "$name\n";
}

Output:

joe
joe123
1joe1234
joe

Demo on 3v4l.org


问:
Why do we use matrices?
Why we use matrices instead of just arrays?

If I create an array of vertices of a 3d model and I want to move each vertex left well

```<code>   ArrayList<Vertex> vertex = fillVertecis();
   for(Vertex vertex: vertices){
      vertex.x += 2;
   }

   //or avoiding creating all those objects

   float[] vertices = fillVertecis();

   //asumming we arrange the array like so [x1,y1,z1,x2,y2,z2....]
   int x = 0;
   int y = 1;
   int z = 2;

   for(int i = 0; i < vertices.lenght/3; i+= 3){
      vertices[i+x] += 1;
   }

</code>```

sure  I'm looping through all vertex but don't we have to do the same using matrices?

What advantages do we have using matrices instead of arrays?

答: Try applying rotation or scaling to your vertices and you'll see the benefit of 4x4 matrices and homogeneous transformations over arrays.</p>

Title: Why do we use matrices?

Body:
Why we use matrices instead of just arrays?

If I create an array of vertices of a 3d model and I want to move each vertex left well

   ArrayList<Vertex> vertex = fillVertecis();
   for(Vertex vertex: vertices){
      vertex.x += 2;
   }

   //or avoiding creating all those objects

   float[] vertices = fillVertecis();

   //asumming we arrange the array like so [x1,y1,z1,x2,y2,z2....]
   int x = 0;
   int y = 1;
   int z = 2;

   for(int i = 0; i < vertices.lenght/3; i+= 3){
      vertices[i+x] += 1;
   }

sure  I'm looping through all vertex but don't we have to do the same using matrices?

What advantages do we have using matrices instead of arrays?


问:
Save a picture in wrong folder using opencv
Directory I would need to save to:

```<code>DataBase-Faces\name
</code>```

Directory where the code is saving:

```<code>DataBase-Faces
</code>```

My code:

```<code>cv2.imwrite("DataBase-Faces\\"+name+str(frames)+".png",Faceimage)
</code>```

My program creates a folder with the typed name, I have to record these images in that folder, and the name of each image will be called Nome Typed + (frame number) .png

答:
General the Code to save the image is something like that

```<code>cv2.imwrite('file.png',img)
</code>```

For the 'file.png' u want to be

EXAMPLE

```<code>name = 'my_photo_album_name'
frames = 500
frame_name = f'{name}\{frames}'
cv2.imwrite(f'DataBase-Faces\{frame_name}.png', img)
</code>```

Body:
Directory I would need to save to:

DataBase-Faces\name

Directory where the code is saving:

DataBase-Faces

My code:

cv2.imwrite("DataBase-Faces\\"+name+str(frames)+".png",Faceimage)

My program creates a folder with the typed name, I have to record these images in that folder, and the name of each image will be called Nome Typed + (frame number) .png

Body:
General the Code to save the image is something like that

cv2.imwrite('file.png',img)

For the 'file.png' u want to be

EXAMPLE

name = 'my_photo_album_name'
frames = 500
frame_name = f'{name}\{frames}'
cv2.imwrite(f'DataBase-Faces\{frame_name}.png', img)


问:
Is "type" a function or class?
I'm a little confused about type as it is listed in Built-in Functions in the Python documentation.

However, when I run type(type) and type.__dict__ it looks more like a callable class. Besides that calling isinstance(type, type) returns True. What's going on?

答:
type is a class, a.k.a. a type - the terms are mostly equivalent in Python 3, although the typing module introduced a separate, subtly incompatible usage of the word "type".

It's documented under "built-in functions" because that's the clearest place to document what it does when you call it like a function. There are a bunch of types documented there. If you look at the top of the page, you'll see

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

Title: Is "type" a function or class?


问:
How many rows can the following SQL query return?
sql. There is a table T with an id field (optionally unique) that contains N rows. How many rows can the following SQL query return?

```<code>select * from T
inner join (
    select count(*) as cnt from T
    union all select count(*) as cnt from T
) as TA on TA.cnt = T.id
inner join (
    select count(*) as cnt from T
    union select count(*) as cnt from T
) as TB on TB.cnt = T.id;
</code>```

I have some options:

only N rows

from 0 to N rows

from 2N to 4N rows

or can you name some other options ?

答:
This query returns either no rows or 2 rows (with all three columns having the same value).

Rationale:

The union all subquery (aliased TA) returns 2 rows, each containing the same value, that is the count of records in T.

The union subquery deduplicates its result and returns a single record, also containing the row count of the table

What happens next depends whether there is a record in the table whose id is equal to that number.

If such record exists, then the query returns 2 rows: one for each row generated by the union all subquery.

If there is no such record, the query return no rows at all.

So assuming this dataset:

```<code>id
--
1
2
</code>```

There are two rows in the table, and id 2 exists, so the query gives you two rows with that id.

If we change this to:

```<code>id
--
1
2
3
5
</code>```

There are four rows but not id 4. The query comes up empty.

Body:
sql. There is a table T with an id field (optionally unique) that contains N rows. How many rows can the following SQL query return?

select * from T
inner join (
    select count(*) as cnt from T
    union all select count(*) as cnt from T
) as TA on TA.cnt = T.id
inner join (
    select count(*) as cnt from T
    union select count(*) as cnt from T
) as TB on TB.cnt = T.id;

I have some options:

only N rows

from 0 to N rows

from 2N to 4N rows

or can you name some other options ?

Body:
This query returns either no rows or 2 rows (with all three columns having the same value).

Rationale:

The union all subquery (aliased TA) returns 2 rows, each containing the same value, that is the count of records in T.

The union subquery deduplicates its result and returns a single record, also containing the row count of the table

What happens next depends whether there is a record in the table whose id is equal to that number.

If such record exists, then the query returns 2 rows: one for each row generated by the union all subquery.

If there is no such record, the query return no rows at all.

So assuming this dataset:

id
--
1
2

There are two rows in the table, and id 2 exists, so the query gives you two rows with that id.

If we change this to:

id
--
1
2
3
5

There are four rows but not id 4. The query comes up empty.


问:
Combine multiple Regex.Replace calls
I've got a text processor, which includes hundreds of Regex.Replace calls. Many of them work on the same text. They would for example remove white spaces and unwanted characters, put brackets around numbers, remove black-listed words, etc.

Is there a way to make multiple replacements with different patterns with a single call? I'm wondering about that, because my code currently is quite slow and I guess that would save some cycles.

答:
Yes, here is a simple example:

```<code>myText = new Regex("hello").Replace(myText, "");
myText = new Regex("goodBye").Replace(myText, "");
</code>```

Could be replaced with:

```<code>myText = new Regex("hello|goodbye").Replace(myText, "");
</code>```

This may or may not improve your app's performance. It really depends.

ContentLicense: CC BY-SA 3.0

Title: Combine multiple Regex.Replace calls

Body:
Yes, here is a simple example:

myText = new Regex("hello").Replace(myText, "");
myText = new Regex("goodBye").Replace(myText, "");

Could be replaced with:

myText = new Regex("hello|goodbye").Replace(myText, "");

This may or may not improve your app's performance. It really depends.


问:
Adding multiple arguments in fscanf
I have tried to store multiple arguments through fscanf, although it works for

```<code>while(fscanf(fptr, "%s %*s %*s %*s", mod) == 1){
}
</code>```

It does not work for the following

```<code>while(fscanf(fptr, "%s %s %*s %*s", mod, mod2) == 1){
}
</code>```

Is there anything im doing wrong?

答:
fscanf() returns the number of conversions that were successfully stored.

Hence you should compare the result of the second fscanf() to 2:

```<code>    while (fscanf(fptr, "%s %s %*s %*s", mod, mod2) == 2) {
        ...
    }
</code>```

Note however that the spaces are redundant and the words skipped by the %*s conversion specifiers may just be absent at the end of file without causing a different return value.

Note too that you should tell fscanf the maximum number of bytes to store into the destination arrays mod and mod2 to avoid undefined behavior on unexpectedly large words in the input file:

```<code>    char mod[32], mod2[32];
    while (fscanf(fptr, "%31s %31s %*s %*s", mod, mod2) == 2) {
        ...
    }

</code>```

Title: Adding multiple arguments in fscanf

Body:
I have tried to store multiple arguments through fscanf, although it works for

while(fscanf(fptr, "%s %*s %*s %*s", mod) == 1){
}

It does not work for the following

while(fscanf(fptr, "%s %s %*s %*s", mod, mod2) == 1){
}

Is there anything im doing wrong?

Body:
fscanf() returns the number of conversions that were successfully stored.

Hence you should compare the result of the second fscanf() to 2:

    while (fscanf(fptr, "%s %s %*s %*s", mod, mod2) == 2) {
        ...
    }

Note however that the spaces are redundant and the words skipped by the %*s conversion specifiers may just be absent at the end of file without causing a different return value.

Note too that you should tell fscanf the maximum number of bytes to store into the destination arrays mod and mod2 to avoid undefined behavior on unexpectedly large words in the input file:

    char mod[32], mod2[32];
    while (fscanf(fptr, "%31s %31s %*s %*s", mod, mod2) == 2) {
        ...
    }


问:
Excel - Return value of adjacent cell (which has the highest value)
I'm trying to write a formula to give me the value of a cell which is directly adjacent to that of the highest value within a range. For reference (https://gyazo.com/67e28d9427021c52731f56f72700aaf2) I want to return the name directly above the highest value (between C8 and F8) into cell H8. I've tried both HLOOKUP and VLOOKUP, a combination of Index and Match, but all to no avail.

In most cases there is one number value greater than the rest, but since this has a tied result, I wanted to display both names if possible

Thanks for any advice!

答:
Can you clarify whether you want to return multiple names when two names align with the highest value?  If you just want to go in order from left-to-right whenever there's multiple matching max values you can use:

=INDEX(C7:F7,XMATCH(MAX(C8:F8),C8:F8,0,1))

The INDEX function returns the name based off of the result of XMATCH.  XMATCH here is finding the location of the max value within the array.

To check if there are multiple names that have tied max values you can use =COUNTIF(C8:F8,MAX(C8:F8)).  You would embed the initial formula into an IF statement such as =IF(COUNTIF(C8:F8,MAX(C8:F8))>1,"Tied Max Score",INDEX(C7:F7,XMATCH(MAX(C8:F8),C8:F8,0,1))).

If you want the result of your formula to return multiple names you'll need to use an array formula.  There are several other posts on this site that answer how to do that.


问:
How do I check if a DataFrame column value exists in any of multiple lists, and if not, fill another column?
I'm trying to fill df['Group'] with either 'boys', 'girls', or 'both' if their respective df['Color'] values exist within any of the lists or fill NaN in df['Group'] if the df['Color'] value doesn't exist in any of the lists.

I have this:

```<code>boys = ['Brown', 'Green']
girls = ['Violet', 'Verde']
both ['Black', 'White']

           Color | Group
    ---------------------
    0  | 'Brown' |   NaN
    1  | 'Green' |   NaN
    2  | 'Black' |   NaN
    3  | 'White' |   NaN
    4  | 'Verde' |   NaN
    5  | 'Purple'|   NaN
    6  | 'Violet'|   NaN
</code>```

I want this:

```<code>           Color | Group
    ---------------------
    0  | 'Brown' |   'boys'
    1  | 'Green' |   'boys'
    2  | 'Black' |   'both'
    3  | 'White' |   'both'
    4  | 'Verde' |   'girls'
    5  | 'Purple'|   NaN
    6  | 'Violet'|   'girls'
</code>```

答:
You can create a dictionary:

```<code>dct = dict(boys = ['Brown', 'Green'],
           girls = ['Violet', 'Verde'],
           both = ['Black', 'White'])

dct = {i: k for k, v in dct.items() for i in v}
</code>```

Output:

```<code>{'Brown': 'boys',
 'Green': 'boys',
 'Violet': 'girls',
 'Verde': 'girls',
 'Black': 'both',
 'White': 'both'}
</code>```

Then you can use the method map:

```<code>df['Group'] = df['Color'].map(dct)
</code>```

Output:

```<code>    Color  Group
0   Brown   boys
1   Green   boys
2   Black   both
3   White   both
4   Verde  girls
5  Purple    NaN
6  Violet  girls
</code>```

Body:
I'm trying to fill df['Group'] with either 'boys', 'girls', or 'both' if their respective df['Color'] values exist within any of the lists or fill NaN in df['Group'] if the df['Color'] value doesn't exist in any of the lists.

I have this:

boys = ['Brown', 'Green']
girls = ['Violet', 'Verde']
both ['Black', 'White']

           Color | Group
    ---------------------
    0  | 'Brown' |   NaN
    1  | 'Green' |   NaN
    2  | 'Black' |   NaN
    3  | 'White' |   NaN
    4  | 'Verde' |   NaN
    5  | 'Purple'|   NaN
    6  | 'Violet'|   NaN

I want this:

           Color | Group
    ---------------------
    0  | 'Brown' |   'boys'
    1  | 'Green' |   'boys'
    2  | 'Black' |   'both'
    3  | 'White' |   'both'
    4  | 'Verde' |   'girls'
    5  | 'Purple'|   NaN
    6  | 'Violet'|   'girls'

Body:
You can create a dictionary:

dct = dict(boys = ['Brown', 'Green'],
           girls = ['Violet', 'Verde'],
           both = ['Black', 'White'])

dct = {i: k for k, v in dct.items() for i in v}

Output:

{'Brown': 'boys',
 'Green': 'boys',
 'Violet': 'girls',
 'Verde': 'girls',
 'Black': 'both',
 'White': 'both'}

Then you can use the method map:

df['Group'] = df['Color'].map(dct)

Output:

    Color  Group
0   Brown   boys
1   Green   boys
2   Black   both
3   White   both
4   Verde  girls
5  Purple    NaN
6  Violet  girls


问:
Using 'repeated' inside 'repeated' data in Nanopb
How to properly encode data with NanoPB when having several nested 'repeated' fields?

This is my schema:

```<code>message Report {

  message SensorData {
     required uint32 sensorid = 1;
     required uint32 sample = 2;
  }

  message DeviceData {
    required uint32 devid = 1;
    repeated SensorData sensor_data = 2;
  }

  required uint32 reportnum = 1;
  repeated DeviceData dev_data = 2;

}
</code>```

I have already made a working version in which SensorData fields are embedded inside DeviceData message based on the server.c example from the NanoPB source. This way I have only one repeated field and everything works fine. However this way I have to repeat the 'devid' field for every sensorid and every 'sample', instead of giving it just one time and then loop through an array of SensorData messages. However I am struggling to encode this with NanoPB, the decoding part is in Python. Can someone give me an example how to properly encode data in this case?

答:
For me the simplest way to do this was by statically defining the size of the array's using a nanopb options file. After that you can access each element just like an array.

report.dev_data[i].devid[j] = 1234;
report.dev_data[i].sensor_data[j] = 9876;
```

Body:
How to properly encode data with NanoPB when having several nested 'repeated' fields?

This is my schema:

message Report {

  message SensorData {
     required uint32 sensorid = 1;
     required uint32 sample = 2;
  }

  message DeviceData {
    required uint32 devid = 1;
    repeated SensorData sensor_data = 2;
  }

  required uint32 reportnum = 1;
  repeated DeviceData dev_data = 2;

}

I have already made a working version in which SensorData fields are embedded inside DeviceData message based on the server.c example from the NanoPB source. This way I have only one repeated field and everything works fine. However this way I have to repeat the 'devid' field for every sensorid and every 'sample', instead of giving it just one time and then loop through an array of SensorData messages. However I am struggling to encode this with NanoPB, the decoding part is in Python. Can someone give me an example how to properly encode data in this case?


问:
How to implement a binary search tree in Python?
This is what I've got so far but it is not working:</p>

```<code>class Node:
    rChild,lChild,data = None,None,None

    def __init__(self,key):
        self.rChild = None
        self.lChild = None
        self.data = key

class Tree:
    root,size = None,0
    def __init__(self):
        self.root = None
        self.size = 0

    def insert(self,node,someNumber):
        if node is None:
            node = Node(someNumber)
        else:
            if node.data > someNumber:
                self.insert(node.rchild,someNumber)
            else:
                self.insert(node.rchild, someNumber)
        return

def main():
    t = Tree()
    t.root = Node(4)
    t.root.rchild = Node(5)
    print t.root.data #this works
    print t.root.rchild.data #this works too
    t = Tree()
    t.insert(t.root,4)
    t.insert(t.root,5)
    print t.root.data #this fails
    print t.root.rchild.data #this fails too

if __name__ == '__main__':
     main()
</code>```

答:
```<code>class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    def add_node(self, node, value):
        """
        Node points to the left of value if node > value; right otherwise,
        BST cannot have duplicate values
        """
        if node is not None:
            if value < node.value:
                if node.left is None:
                    node.left = TreeNode(value)
                else:
                    self.add_node(node.left, value)
            else:
                if node.right is None:
                    node.right = TreeNode(value)
                else:
                    self.add_node(node.right, value)
        else:
            self.root = TreeNode(value)

    def search(self, value):
        """
        Value will be to the left of node if node > value; right otherwise.
        """
        node = self.root
        while node is not None:
            if node.value == value:
                return True     # node.value
            if node.value > value:
                node = node.left
            else:
                node = node.right
        return False

    def traverse_inorder(self, node):
        """
        Traverse the left subtree of a node as much as possible, then traverse
        the right subtree, followed by the parent/root node.
        """
        if node is not None:
            self.traverse_inorder(node.left)
            print(node.value)
            self.traverse_inorder(node.right)

def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(binary_tree.root, 200)
    binary_tree.add_node(binary_tree.root, 300)
    binary_tree.add_node(binary_tree.root, 100)
    binary_tree.add_node(binary_tree.root, 30)
    binary_tree.traverse_inorder(binary_tree.root)
    print(binary_tree.search(200))

if __name__ == '__main__':
    main()
</code>```

Body:
This is what I've got so far but it is not working:

class Node:
    rChild,lChild,data = None,None,None

    def __init__(self,key):
        self.rChild = None
        self.lChild = None
        self.data = key

class Tree:
    root,size = None,0
    def __init__(self):
        self.root = None
        self.size = 0

    def insert(self,node,someNumber):
        if node is None:
            node = Node(someNumber)
        else:
            if node.data > someNumber:
                self.insert(node.rchild,someNumber)
            else:
                self.insert(node.rchild, someNumber)
        return

def main():
    t = Tree()
    t.root = Node(4)
    t.root.rchild = Node(5)
    print t.root.data #this works
    print t.root.rchild.data #this works too
    t = Tree()
    t.insert(t.root,4)
    t.insert(t.root,5)
    print t.root.data #this fails
    print t.root.rchild.data #this fails too

if __name__ == '__main__':
     main()


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答: Stack vs Heap: What goes where, what caused a StackOverflowException and what causes an OutOfMemoryException.

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: C. Ross


问:
SQL - Need help filtering results based on rows
I have a table that looks like this:

```<code>p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1
</code>```

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

答:
```<code>SELECT p_id
FROM Mytable
WHERE comp_id IN (1,2)
GROUP BY p_id
HAVING COUNT(distinct comp_id) = 2
</code>```

Ensure your IN contains the same number of values as the int in the HAVING clause.

Body:
I have a table that looks like this:

p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

Body:
SELECT p_id
FROM Mytable
WHERE comp_id IN (1,2)
GROUP BY p_id
HAVING COUNT(distinct comp_id) = 2

Ensure your IN contains the same number of values as the int in the HAVING clause.


问:
Creating a seeder in Laravel 6 that works with foreign key constraint
I am trying to create a seeder that fills a databases with "Assignments" that are linked with a "Course" database with foreign key constraint.
Since i am pretty new to PHP and Laravel 6 in general i don't really know where to start.
I allready have a seeder that fills my "Course" database, which like this:

```<code>class  CoursesTableSeed extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('courses')->insert([[
            'name' => 'Opleidings- en beroepsoriëntatie',
            'ecs' => '2.5'
        ],[
            'name' => 'Computer science basics',
            'ecs' => '7.5'
        ],[
            'name' => 'Programming basics',
            'ecs' => '5'
        ],[
            'name'=>'Professional skills 1',
            'ecs'=>'2.5',

        ],[
            'name'=>'HZ Personality',
            'ecs'=>'2.5',

        ],[
            'name'=>'Object-oriented programming',
            'ecs'=>'10',

        ],[
            'name'=>'Professional skills 2',
            'ecs'=>'2.5',

        ],[
            'name'=>'Professionele werkplek',
            'ecs'=>'2.5',

        ],[
            'name'=>'Framework development 1',
            'ecs'=>'5',

        ],[
            'name'=>'Framework project 1',
            'ecs'=>'5',

        ],[
            'name'=>'Professional skills 3',
            'ecs'=>'2.5',

        ],[
            'name'=>'IT Personality 1',
            'ecs'=>'2.5',

        ],[
            'name'=>'Framework development 2',
            'ecs'=>'5',

        ],[
            'name'=>'Framework project 2',
            'ecs'=>'5',

        ]
        ]);
    }
}
</code>```

Now i want to do the same thing with my assignment database but i cant figure out how since i also want to have the "Assignments" linked with theyr respective "Course" so when i delete a course it also deletes it associated assignments. If this question comes over a little vague, sorry for that. I am pretty new to PHP laravel and programming in general.
Also, this is my migration for the assignments:

```<code>class CreateAssignmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('assignments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('course_id');
            $table->text('name');
            $table->decimal('weight',3,1)->nullable();
            $table->decimal('grade', 3, 1)->nullable();
            $table->timestamps();

            $table->foreign('course_id')
                ->references('id')
                ->on('courses')
                ->onDelete('cascade');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('assignments');
    }
}
</code>```

答:
Welcome to Stackoverflow!
You can seed your assignments in different ways. For example: update existing seeder, or create another seeder.

Here code for another seeder (you must have Course and Assignment models):

```<code><?php

use App\Assignment;
use App\Course;
use Illuminate\Database\Seeder;

class AssignmentsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $data = [
            [
                'name' => 'Opleidings- en beroepsoriëntatie',
                'assignments' => [
                    [
                        'name' => 'Assignment 1',
                        'weight' => 1.5,
                        'grade' => 1.1,
                    ],
                    [
                        'name' => 'Assignment 2',
                        'weight' => 2.0,
                        'grade' => 1.2,
                    ],
                ]
            ],
            [
                'name' => 'Computer science basics',
                'assignments' => [
                    [
                        'name' => 'Assignment 3',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                    [
                        'name' => 'Assignment 4',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                    [
                        'name' => 'Assignment 5',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                ]
            ],
        ];

        // Loops through courses
        foreach ($data as $key => $value) {
            $course = Course::where('name', $value['name'])->first();

            if ($course instanceof Course) {
                if (isset($value['assignments']) && is_array($value['assignments'])) {
                    // Loops through assignments
                    foreach ($value['assignments'] as $assignment) {
                        $assignment['course_id'] = $course->id;
                        Assignment::firstOrCreate($assignment);
                    }
                }
            }
        }
    }
}

</code>```

Put this code to database/seeds/AssignmentsTableSeeder.php file and after that call this console commands:

composer dump-autoload

php artisan db:seed --class=AssignmentsTableSeeder

After that you will get the following result

Body:
I am trying to create a seeder that fills a databases with "Assignments" that are linked with a "Course" database with foreign key constraint.
Since i am pretty new to PHP and Laravel 6 in general i don't really know where to start.
I allready have a seeder that fills my "Course" database, which like this:

class  CoursesTableSeed extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('courses')->insert([[
            'name' => 'Opleidings- en beroepsoriëntatie',
            'ecs' => '2.5'
        ],[
            'name' => 'Computer science basics',
            'ecs' => '7.5'
        ],[
            'name' => 'Programming basics',
            'ecs' => '5'
        ],[
            'name'=>'Professional skills 1',
            'ecs'=>'2.5',

        ],[
            'name'=>'HZ Personality',
            'ecs'=>'2.5',

        ],[
            'name'=>'Object-oriented programming',
            'ecs'=>'10',

        ],[
            'name'=>'Professional skills 2',
            'ecs'=>'2.5',

        ],[
            'name'=>'Professionele werkplek',
            'ecs'=>'2.5',

        ],[
            'name'=>'Framework development 1',
            'ecs'=>'5',

        ],[
            'name'=>'Framework project 1',
            'ecs'=>'5',

        ],[
            'name'=>'Professional skills 3',
            'ecs'=>'2.5',

        ],[
            'name'=>'IT Personality 1',
            'ecs'=>'2.5',

        ],[
            'name'=>'Framework development 2',
            'ecs'=>'5',

        ],[
            'name'=>'Framework project 2',
            'ecs'=>'5',

        ]
        ]);
    }
}

Now i want to do the same thing with my assignment database but i cant figure out how since i also want to have the "Assignments" linked with theyr respective "Course" so when i delete a course it also deletes it associated assignments. If this question comes over a little vague, sorry for that. I am pretty new to PHP laravel and programming in general.
Also, this is my migration for the assignments:

class CreateAssignmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('assignments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('course_id');
            $table->text('name');
            $table->decimal('weight',3,1)->nullable();
            $table->decimal('grade', 3, 1)->nullable();
            $table->timestamps();

            $table->foreign('course_id')
                ->references('id')
                ->on('courses')
                ->onDelete('cascade');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('assignments');
    }
}

Body:
Welcome to Stackoverflow!
You can seed your assignments in different ways. For example: update existing seeder, or create another seeder.

Here code for another seeder (you must have Course and Assignment models):

<?php

use App\Assignment;
use App\Course;
use Illuminate\Database\Seeder;

class AssignmentsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $data = [
            [
                'name' => 'Opleidings- en beroepsoriëntatie',
                'assignments' => [
                    [
                        'name' => 'Assignment 1',
                        'weight' => 1.5,
                        'grade' => 1.1,
                    ],
                    [
                        'name' => 'Assignment 2',
                        'weight' => 2.0,
                        'grade' => 1.2,
                    ],
                ]
            ],
            [
                'name' => 'Computer science basics',
                'assignments' => [
                    [
                        'name' => 'Assignment 3',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                    [
                        'name' => 'Assignment 4',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                    [
                        'name' => 'Assignment 5',
                        'weight' => 1.5,
                        'grade' => 1.0,
                    ],
                ]
            ],
        ];

        // Loops through courses
        foreach ($data as $key => $value) {
            $course = Course::where('name', $value['name'])->first();

            if ($course instanceof Course) {
                if (isset($value['assignments']) && is_array($value['assignments'])) {
                    // Loops through assignments
                    foreach ($value['assignments'] as $assignment) {
                        $assignment['course_id'] = $course->id;
                        Assignment::firstOrCreate($assignment);
                    }
                }
            }
        }
    }
}

Put this code to database/seeds/AssignmentsTableSeeder.php file and after that call this console commands:

composer dump-autoload

php artisan db:seed --class=AssignmentsTableSeeder

After that you will get the following result


问:
Ready event for templates
In JsViews i can bind events in the following way:

```<code><li id="myElement" data-link="{on 'click' eventHandler}">Some Content</li>
</code>```

This will execute the method "eventHandler" after a click.
But I need an event which will be fired when the template is loaded. I tried "ready" or "show", but nothings works. Is there a event which can handle this?

答:
You could use an onload event:-

https://www.w3schools.com/jsref/event_onload.asp

and attach that to the template itself. If you're limited in your options or need to do it in a specific way, explain the use case and why you want to do it a certain way and we'll try to help.
All the best,

Phil

Title: Ready event for templates

Body:
In JsViews i can bind events in the following way:

Some Content

This will execute the method "eventHandler" after a click.
But I need an event which will be fired when the template is loaded. I tried "ready" or "show", but nothings works. Is there a event which can handle this?


问:
Remove numbers if greater than X - PHP
I am removing numbers from $name, as follows:

```<code>$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
</code>```

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

答:
No Preg match solution:

```<code><?php function searchAndReplace($array, $string, $max_search)
{
    $count = 0;
    foreach ($array as $arr) {
        $count += substr_count($string, $arr);
        if ($count >= $max_search) return str_replace($array,'',$string);
    }
    return $string;
}
function removeNumbers($string)
{
    $array = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    return searchAndReplace($array, $string, 6);
}
echo removeNumbers('joe123456'); //joe
echo removeNumbers('joe123'); //joe123
echo removeNumbers('1joe1234'); //1joe1234
</code>```

Title: Remove numbers if greater than X - PHP

Body:
I am removing numbers from $name, as follows:

$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

Body:
No Preg match solution:

<?php function searchAndReplace($array, $string, $max_search)
{
    $count = 0;
    foreach ($array as $arr) {
        $count += substr_count($string, $arr);
        if ($count >= $max_search) return str_replace($array,'',$string);
    }
    return $string;
}
function removeNumbers($string)
{
    $array = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    return searchAndReplace($array, $string, 6);
}
echo removeNumbers('joe123456'); //joe
echo removeNumbers('joe123'); //joe123
echo removeNumbers('1joe1234'); //1joe1234


问:
Looking for a regex pattern between a range of 0.1 to 24. Need to allow for 2 decimal places
I can't seem to get a regex to work that will allow a user to enter a float between the range of 0.1 to 24.  I need to allow 2 decimal places and it must be greater than 0 and less than 24.    </p>

Body:
/^(?:(?:0\.[1-9]\d?)|1\d?(?:(?:\.\d\d?)?)|2[0-3]?(?:(?:\.\d\d?)?))$/

you can view it on  https://rubular.com/r/NezAGzQ3GPWWai


问:
How to open a drawer in flutter test
I am trying to test a custom drawer but find it hard opening it in the test, tried the following to begin with and even this test doesn't pass. The error is: Bad state: no element.

```<code>void main() {
  testWidgets('my drawer test', (WidgetTester tester) async {
    final displayName = "displayName";
    var drawKey = UniqueKey();
    await tester.pumpWidget(MaterialApp(
        home: Scaffold(
      drawer: Drawer(key: drawKey, child: Text(displayName),),
    )));
    await tester.tap(find.byKey(drawKey));
    expect(find.text(displayName), findsOneWidget);
  });
}
</code>```

答:
You can grab the top left of the parent widget and use dragFrom in order to simulate opening the drawer. In comparison to the current accepted answer, this does not require you to pass the scaffold key.

An example with a slight modification of the original code:

```<code>testWidgets('my drawer test', (WidgetTester tester) async {
  final displayName = "displayName";
  var drawKey = UniqueKey();
  await tester.pumpWidget(MaterialApp(
    home: Scaffold(
      drawer: Drawer(key: drawKey, child: Text(displayName),),
    )));

  await tester.dragFrom(tester.getTopLeft(find.byType(MaterialApp)), Offset(300, 0));
  await tester.pumpAndSettle();

  expect(find.text(displayName), findsOneWidget);
});
</code>```

Notice tester.pumpAndSettle() was added to ensure enough time has passed.

Title: How to open a drawer in flutter test

Body:
I am trying to test a custom drawer but find it hard opening it in the test, tried the following to begin with and even this test doesn't pass. The error is: Bad state: no element.

void main() {
  testWidgets('my drawer test', (WidgetTester tester) async {
    final displayName = "displayName";
    var drawKey = UniqueKey();
    await tester.pumpWidget(MaterialApp(
        home: Scaffold(
      drawer: Drawer(key: drawKey, child: Text(displayName),),
    )));
    await tester.tap(find.byKey(drawKey));
    expect(find.text(displayName), findsOneWidget);
  });
}

Body:
You can grab the top left of the parent widget and use dragFrom in order to simulate opening the drawer. In comparison to the current accepted answer, this does not require you to pass the scaffold key.

An example with a slight modification of the original code:

testWidgets('my drawer test', (WidgetTester tester) async {
  final displayName = "displayName";
  var drawKey = UniqueKey();
  await tester.pumpWidget(MaterialApp(
    home: Scaffold(
      drawer: Drawer(key: drawKey, child: Text(displayName),),
    )));

  await tester.dragFrom(tester.getTopLeft(find.byType(MaterialApp)), Offset(300, 0));
  await tester.pumpAndSettle();

  expect(find.text(displayName), findsOneWidget);
});

Notice tester.pumpAndSettle() was added to ensure enough time has passed.


问:
LSL but updating right bits with 1 rather than 0
I need an instruction similar to LSL but the bits on the right must be filled with 1 rather then 0.
Something like: </p>

```<code>mov x0, 1
XXX x0, 3 -> here I should have 1111 in x0.
</code>```

答:
Unfortunately no, there isn't a single instruction that will do this. From your example, it's hard to say if you want something like the arithmetic right shift that will fill based on the least significant bit (either one or zero depending on the value of the LSb) or just an always fill with ones instead of zeroes. Either way, you can achieve similar result in 2/3 instructions:</p>

```<code>MOV x0, #1

/* For the fill with LSb case */
RBIT x0, x0  /* reverse the bit order of the register */
ASR x0, x0, #3 /* use arithmetic right shift to do the shift, it will fill with the old LSb, now MSb */
RBIT x0, x0 /* fill bits back */

/* For the fill with 1s case */
MVN x0, x0 /* bitwise not the value of the register */
MVN x0, x0, LSL #3 /* shift the register value, filling with 0s, then invert the register again, restoring the original bits and flipping the filled 0s to 1s */

/* From the comments, it looks like OP wants the shift to come from another register and not a constant like in their post so the above needs an extra instruction */
MOV x1, #3 /* load the shift amount into a register */
MVN x0, x0
LSL x0, x0, x1 /* need a separate instruction to use a register instead of a constant as the shift amount */
MVN x0, x0
</code>```

Body:
I need an instruction similar to LSL but the bits on the right must be filled with 1 rather then 0.
Something like:

mov x0, 1
XXX x0, 3 -> here I should have 1111 in x0.

Body:
Unfortunately no, there isn't a single instruction that will do this. From your example, it's hard to say if you want something like the arithmetic right shift that will fill based on the least significant bit (either one or zero depending on the value of the LSb) or just an always fill with ones instead of zeroes. Either way, you can achieve similar result in 2/3 instructions:

MOV x0, #1

/* For the fill with LSb case */
RBIT x0, x0  /* reverse the bit order of the register */
ASR x0, x0, #3 /* use arithmetic right shift to do the shift, it will fill with the old LSb, now MSb */
RBIT x0, x0 /* fill bits back */

/* For the fill with 1s case */
MVN x0, x0 /* bitwise not the value of the register */
MVN x0, x0, LSL #3 /* shift the register value, filling with 0s, then invert the register again, restoring the original bits and flipping the filled 0s to 1s */

/* From the comments, it looks like OP wants the shift to come from another register and not a constant like in their post so the above needs an extra instruction */
MOV x1, #3 /* load the shift amount into a register */
MVN x0, x0
LSL x0, x0, x1 /* need a separate instruction to use a register instead of a constant as the shift amount */
MVN x0, x0


问:
Pandas DENSE RANK
I'm dealing with pandas dataframe and have a frame like this:

```<code>Year Value
2012  10
2013  20
2013  25
2014  30
</code>```

I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:

```<code>    Year Value Rank
    2012  10    1
    2013  20    2
    2013  25    2
    2014  30    3
</code>```

How can it be done in pandas?

Thanks!

答:
Groupby.ngroup

Will sort keys by default so smaller years get labeled lower. Can set sort=False to rank groups based on order of occurrence.

```<code>df['Rank'] = df.groupby('Year', sort=True).ngroup()+1
</code>```

np.unique

Also sorts, so use return_inverse to rank the smaller values lowest.

```<code>df['Rank'] = np.unique(df['Year'], return_inverse=True)[1]+1
</code>```

Title: Pandas DENSE RANK

Body:
I'm dealing with pandas dataframe and have a frame like this:

Year Value
2012  10
2013  20
2013  25
2014  30

I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:

    Year Value Rank
    2012  10    1
    2013  20    2
    2013  25    2
    2014  30    3

How can it be done in pandas?

Thanks!

Body:
Groupby.ngroup

Will sort keys by default so smaller years get labeled lower. Can set sort=False to rank groups based on order of occurrence.

df['Rank'] = df.groupby('Year', sort=True).ngroup()+1

np.unique

Also sorts, so use return_inverse to rank the smaller values lowest.

df['Rank'] = np.unique(df['Year'], return_inverse=True)[1]+1


问:
matching row values (text) with column names and return value
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

```<code>region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396
</code>```

And I want to get something that looks like this:

```<code>region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA
</code>```

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

答:
Here is one option with tidyverse where we reshape into 'long' format with pivot_longer, replace the elements in 'value' where the 'region' is not equal to 'name' column value and then reshape back to 'wide' format

```<code>library(dplyr)
library(tidyr)
df1 %>%
  pivot_longer(cols = -region) %>%
  mutate(value = replace(value, name!= region, NA)) %>%
  pivot_wider(names_from = name, values_from = value)
#   region   A  B   C  D   E   F
#1       H  NA NA  NA NA  NA  NA
#2       J  NA NA  NA NA  NA  NA
#3       A 820 NA  NA NA  NA  NA
#4       X  NA NA  NA NA  NA  NA
#5       M  NA NA  NA NA  NA  NA
#6       N  NA NA  NA NA  NA  NA
#7       C  NA NA 952 NA  NA  NA
#8       L  NA NA  NA NA  NA  NA
#9       E  NA NA  NA NA 944  NA
#10      F  NA NA  NA NA  NA 616
#11      P  NA NA  NA NA  NA  NA
#12      Q  NA NA  NA NA  NA  NA
</code>```

Another option is imap

```<code>library(purrr)
imap_dfc(df1[-1], ~ replace(.x, .y != df1[['region']], NA)) %>%
   bind_cols(df1['region'], .)
#    region   A  B   C  D   E   F
#1       H  NA NA  NA NA  NA  NA
#2       J  NA NA  NA NA  NA  NA
#3       A 820 NA  NA NA  NA  NA
#4       X  NA NA  NA NA  NA  NA
#5       M  NA NA  NA NA  NA  NA
#6       N  NA NA  NA NA  NA  NA
#7       C  NA NA 952 NA  NA  NA
#8       L  NA NA  NA NA  NA  NA
#9       E  NA NA  NA NA 944  NA
#10      F  NA NA  NA NA  NA 616
#11      P  NA NA  NA NA  NA  NA
#12      Q  NA NA  NA NA  NA  NA
</code>```

Or using base R, we replicate the names of the dataset and do a comparison with the 'region' column, change those values in those columns to NA based on the comparison

```<code>df1[-1] <- NA^(df1$region != names(df1)[-1][col(df1[-1])]) * df1[-1]
</code>```

data

```<code>df1 <- structure(list(region = c("H", "J", "A", "X", "M", "N", "C",
"L", "E", "F", "P", "Q"), A = c(796L, 568L, 820L, 292L, 872L,
100L, 940L, 960L, 980L, 236L, 796L, 568L), B = c(792L, 564L,
804L, 272L, 812L, 992L, 948L, 956L, 968L, 364L, 792L, 564L),
    C = c(844L, 508L, 748L, 260L, 792L, 972L, 952L, 952L, 956L,
    460L, 844L, 508L), D = c(812L, 268L, 528L, 324L, 760L, 880L,
    916L, 920L, 940L, 524L, 812L, 268L), E = c(796L, 320L, 560L,
    224L, 668L, 872L, 864L, 900L, 944L, 552L, 796L, 320L), F = c(776L,
    396L, 600L, 200L, 656L, 864L, 880L, 920L, 932L, 616L, 776L,
    396L)), class = "data.frame", row.names = c(NA, -12L))
</code>```

Body:
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396

And I want to get something that looks like this:

region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
Here is one option with tidyverse where we reshape into 'long' format with pivot_longer, replace the elements in 'value' where the 'region' is not equal to 'name' column value and then reshape back to 'wide' format

library(dplyr)
library(tidyr)
df1 %>%
  pivot_longer(cols = -region) %>%
  mutate(value = replace(value, name!= region, NA)) %>%
  pivot_wider(names_from = name, values_from = value)
#   region   A  B   C  D   E   F
#1       H  NA NA  NA NA  NA  NA
#2       J  NA NA  NA NA  NA  NA
#3       A 820 NA  NA NA  NA  NA
#4       X  NA NA  NA NA  NA  NA
#5       M  NA NA  NA NA  NA  NA
#6       N  NA NA  NA NA  NA  NA
#7       C  NA NA 952 NA  NA  NA
#8       L  NA NA  NA NA  NA  NA
#9       E  NA NA  NA NA 944  NA
#10      F  NA NA  NA NA  NA 616
#11      P  NA NA  NA NA  NA  NA
#12      Q  NA NA  NA NA  NA  NA

Another option is imap

library(purrr)
imap_dfc(df1[-1], ~ replace(.x, .y != df1[['region']], NA)) %>%
   bind_cols(df1['region'], .)
#    region   A  B   C  D   E   F
#1       H  NA NA  NA NA  NA  NA
#2       J  NA NA  NA NA  NA  NA
#3       A 820 NA  NA NA  NA  NA
#4       X  NA NA  NA NA  NA  NA
#5       M  NA NA  NA NA  NA  NA
#6       N  NA NA  NA NA  NA  NA
#7       C  NA NA 952 NA  NA  NA
#8       L  NA NA  NA NA  NA  NA
#9       E  NA NA  NA NA 944  NA
#10      F  NA NA  NA NA  NA 616
#11      P  NA NA  NA NA  NA  NA
#12      Q  NA NA  NA NA  NA  NA

Or using base R, we replicate the names of the dataset and do a comparison with the 'region' column, change those values in those columns to NA based on the comparison

df1[-1] <- NA^(df1$region != names(df1)[-1][col(df1[-1])]) * df1[-1]

data

df1 <- structure(list(region = c("H", "J", "A", "X", "M", "N", "C",
"L", "E", "F", "P", "Q"), A = c(796L, 568L, 820L, 292L, 872L,
100L, 940L, 960L, 980L, 236L, 796L, 568L), B = c(792L, 564L,
804L, 272L, 812L, 992L, 948L, 956L, 968L, 364L, 792L, 564L),
    C = c(844L, 508L, 748L, 260L, 792L, 972L, 952L, 952L, 956L,
    460L, 844L, 508L), D = c(812L, 268L, 528L, 324L, 760L, 880L,
    916L, 920L, 940L, 524L, 812L, 268L), E = c(796L, 320L, 560L,
    224L, 668L, 872L, 864L, 900L, 944L, 552L, 796L, 320L), F = c(776L,
    396L, 600L, 200L, 656L, 864L, 880L, 920L, 932L, 616L, 776L,
    396L)), class = "data.frame", row.names = c(NA, -12L))


问:
Auto generate IDs for MongoDB sub-documents in array with Spring MongoTemplate
My MongoDB document structure for a post is like this

```<code>{
"_id" : ObjectId("5e487ce64787a51f073d0915"),
"active" : true,
"datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
"likes" : 400,
"commentList" : [
    {
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I read all your posts and always think they don't make any sense",
        "likes" : 368
    },
    {
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I enjoy all your posts and are great way to kill time",
        "likes" : 3533
    }
}
</code>```

And there corresponding entity classes

CommentEntity.java

```<code>public class CommentEntity{

  private String id;
  private LocalDateTime datePosted;
  private String comment;
  private int likes;

  ....

}
</code>```

PostEntity.java

```<code>@Document(collection = "post")
public class PostEntity {

  @Id
  private String id;
  private boolean active;
  private LocalDateTime datePosted;
  private int likes;
  private List<CommentEntity> commentList;

  ....

}
</code>```

I am using Spring Data MongoTemplate for inserts. How can I configure MongoTemplate to auto generate _id for comments as well when they are inserted into post document, something like below

```<code>{
"_id" : ObjectId("5e487ce64787a51f073d0915"),
"active" : true,
"datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
"likes" : 400,
"commentList" : [
    {
        "_id" : ObjectId("5e487ce64787a51f07snd315"),
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I read all your posts and always think they don't make any sense",
        "likes" : 368
    },
    {
        "_id" : ObjectId("5e48764787a51f07snd5j4hb4k"),
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I enjoy all your posts and are great way to kill time",
        "likes" : 3533
    }
}
</code>```

答:
Spring Data maps your classes into MongoDB documents. During the mapping, only _id can be generated automatically.

MongoDB requires that you have an '_id' field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value. A field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field.

A field without an annotation but named id will be mapped to the _id field.

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping.conventions.id-field

Workaround:

Instance new ObjectId for id field and convention will convert id to _id.

```<code>public class CommentEntity {

    private String id;
    private LocalDateTime datePosted;
    private String comment;
    private int likes;

    ....

    public CommentEntity() {
        id = new ObjectId().toString();
        ...
    }

}
</code>```

Body:
My MongoDB document structure for a post is like this

{
"_id" : ObjectId("5e487ce64787a51f073d0915"),
"active" : true,
"datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
"likes" : 400,
"commentList" : [
    {
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I read all your posts and always think they don't make any sense",
        "likes" : 368
    },
    {
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I enjoy all your posts and are great way to kill time",
        "likes" : 3533
    }
}

And there corresponding entity classes

CommentEntity.java

public class CommentEntity{

  private String id;
  private LocalDateTime datePosted;
  private String comment;
  private int likes;

  ....

}

PostEntity.java

@Document(collection = "post")
public class PostEntity {

  @Id
  private String id;
  private boolean active;
  private LocalDateTime datePosted;
  private int likes;
  private List<CommentEntity> commentList;

  ....

}

I am using Spring Data MongoTemplate for inserts. How can I configure MongoTemplate to auto generate _id for comments as well when they are inserted into post document, something like below

{
"_id" : ObjectId("5e487ce64787a51f073d0915"),
"active" : true,
"datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
"likes" : 400,
"commentList" : [
    {
        "_id" : ObjectId("5e487ce64787a51f07snd315"),
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I read all your posts and always think they don't make any sense",
        "likes" : 368
    },
    {
        "_id" : ObjectId("5e48764787a51f07snd5j4hb4k"),
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I enjoy all your posts and are great way to kill time",
        "likes" : 3533
    }
}

Body:
Spring Data maps your classes into MongoDB documents. During the mapping, only _id can be generated automatically.

MongoDB requires that you have an '_id' field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value. A field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field.

A field without an annotation but named id will be mapped to the _id field.

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping.conventions.id-field

Workaround:

Instance new ObjectId for id field and convention will convert id to _id.

public class CommentEntity {

    private String id;
    private LocalDateTime datePosted;
    private String comment;
    private int likes;

    ....

    public CommentEntity() {
        id = new ObjectId().toString();
        ...
    }

}


问:
In Rust, is there a function for continuously "folding" a stream, i.e. mapping with state?
I have a futures::stream::Stream of websocket messages that represent state changes, and I want a stream of the state. I've come across the fold method which does something similar, but it collects everything up into one final state, rather than producing a new stream of all the intermediate states.

E.g. I have an initial state "0" and a stream of "increment" and "decrement" events, I want a stream of the resulting numbers.

答:
As Robin Zigmond mentioned in the comments, the Iterator::scan function is probably what you're looking for.

Example:

/// Our "event" type, with increment and decrement events.
#[derive(Debug)]
enum Event {
    Inc,
    Dec,
}

/// For simplicity, the `Event::apply` function will modify our integer
/// depending on the event.
impl Event {
    fn apply(&self, n: i32) -> i32 {
        match self {
            Inc => n + 1,
            Dec => n - 1,
        }
    }
}

/// Import `Event::Inc` and `Event::Dec` into scope so we can access them as
/// simply `Inc` and `Dec`.
use Event::{Inc, Dec};

fn main() {
    // List of events
    let events = &[ Inc, Inc, Dec, Inc, Dec, Dec ];

    let values: Vec<_> = events.iter().scan(0i32, |n, ev| {
        // `n` is a mutable reference to the "state" of the scan.
        // It initially has the value `0i32`, but we can modify it each time
        // the closure is called.
        *n = ev.apply(*n);

        // The closure can return `Some(expr)`, which is the next value of the
        // iterator, or `None` to end early. In our case we just return the state.
        Some(*n)
    }).collect();

    println!("events = {:?}", events); // [Inc, Inc, Dec, Inc, Dec, Dec]
    println!("values = {:?}", values); // [1, 2, 1, 2, 1, 0]
}
```

Playground example

Body:
As Robin Zigmond mentioned in the comments, the Iterator::scan function is probably what you're looking for.

Example:

/// Our "event" type, with increment and decrement events.
#[derive(Debug)]
enum Event {
    Inc,
    Dec,
}

/// For simplicity, the `Event::apply` function will modify our integer
/// depending on the event.
impl Event {
    fn apply(&self, n: i32) -> i32 {
        match self {
            Inc => n + 1,
            Dec => n - 1,
        }
    }
}

/// Import `Event::Inc` and `Event::Dec` into scope so we can access them as
/// simply `Inc` and `Dec`.
use Event::{Inc, Dec};

fn main() {
    // List of events
    let events = &[ Inc, Inc, Dec, Inc, Dec, Dec ];

    let values: Vec<_> = events.iter().scan(0i32, |n, ev| {
        // `n` is a mutable reference to the "state" of the scan.
        // It initially has the value `0i32`, but we can modify it each time
        // the closure is called.
        *n = ev.apply(*n);

        // The closure can return `Some(expr)`, which is the next value of the
        // iterator, or `None` to end early. In our case we just return the state.
        Some(*n)
    }).collect();

    println!("events = {:?}", events); // [Inc, Inc, Dec, Inc, Dec, Dec]
    println!("values = {:?}", values); // [1, 2, 1, 2, 1, 0]
}

Playground example


问:
Can I have an enum with unlabelled values in C++?
Basically I want to restrict variables to the values 0, 1 or 2.

I have tried doing this with the following:

```<code>enum Value
{
    0,
    1,
    2
};
Value var;
</code>```

But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than referring to the values as 0, 1 and 2. Is there any way around this or should I just get rid of the enum and enforce the rule elsewhere?

答:
If you want to use enum, then you need to name them. Since you're just working with integer values, and you apparently want them to actually represent integer values, your best bet is it use an int parameter, and do a quick check at the top of the method. A comment on the method specifying this constraint would be welcome.

Note that if your values actually correspond to non-numeric settings, then you should just come up with good names and use the enum

Body:
Basically I want to restrict variables to the values 0, 1 or 2.

I have tried doing this with the following:

enum Value
{
    0,
    1,
    2
};
Value var;

But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than referring to the values as 0, 1 and 2. Is there any way around this or should I just get rid of the enum and enforce the rule elsewhere?