Title: how to split time stamped data as train and test

Body:
I have a dataset with timestamped given below:

date        type, price
1990-01-01, 'A', 100
1990-01-02, 'A', 200
1990-01-03, 'A', 300
1990-01-04, 'A', 400
1990-01-05, 'A', 500
1990-01-06, 'A', 600
1990-01-07, 'A', 700
1990-01-08, 'A', 800
1990-01-09, 'A', 900
1990-01-10, 'A', 1000
1990-01-11, 'B', 1100
1990-01-12, 'B', 1200
1990-01-13, 'B', 1300
1990-01-14, 'B', 1400
1990-01-15, 'B', 1500

I am trying to split this data as train and test with keeping the order based on date. If the split ratio is 0.8 for train and test, the expected output is supposed to be the following data:
train_data:

date        type, price
1990-01-01, 'A', 100
1990-01-02, 'A', 200
1990-01-03, 'A', 300
1990-01-04, 'A', 400
1990-01-05, 'A', 500
1990-01-06, 'A', 600
1990-01-07, 'A', 700
1990-01-08, 'A', 800
1990-01-11, 'B', 1100
1990-01-12, 'B', 1200
1990-01-13, 'B', 1300
1990-01-14, 'B', 1400

test_data:

    date        type, price
    1990-01-09, 'A', 900
    1990-01-10, 'A', 1000
    1990-01-15, 'B', 1500

Is there any way to do this in a pythonic way?

Body:
You can use groupby and apply methods to split the data.

Code:

import io
import pandas as pd

# Create sample data as string
s = '''date,type,price
1990-01-01,A,100
1990-01-02,A,200
1990-01-03,A,300
1990-01-04,A,400
1990-01-05,A,500
1990-01-06,A,600
1990-01-07,A,700
1990-01-08,A,800
1990-01-09,A,900
1990-01-10,A,1000
1990-01-11,B,1100
1990-01-12,B,1200
1990-01-13,B,1300
1990-01-14,B,1400
1990-01-15,B,1500'''

# Read the sample
df = pd.read_csv(io.StringIO(s))

# Ensure that df is sorted by date at least
df = df.sort_values(['type', 'date']).reset_index(drop=True)

# Split df into train and test dataframes
split_ratio = 0.8
train_data = df.groupby('type', group_keys=False).apply(lambda df: df.head(int(split_ratio * len(df))))
test_data = df[~df.index.isin(train_data.index)]

Output:

# train_data:

date
type
price

0
1990-01-01
A
100

1
1990-01-02
A
200

2
1990-01-03
A
300

3
1990-01-04
A
400

4
1990-01-05
A
500

5
1990-01-06
A
600

6
1990-01-07
A
700

7
1990-01-08
A
800

10
1990-01-11
B
1100

11
1990-01-12
B
1200

12
1990-01-13
B
1300

13
1990-01-14
B
1400

# test_data:

date
type
price

8
1990-01-09
A
900

9
1990-01-10
A
1000

14
1990-01-15
B
1500


来源: stackexchange

问:
Return Missing balancing numbers
A balanced array would be an array in which each element appears the same number of times.

Given an array with n elements:
return a dictionary with the key as the element and the value as the count of elements needed to balance the given array

Examples

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

Expected output: {"b":1, "abc":1, "c":1}

Because there are 2 a, we need 1 more of b, abc, c

Hope that helps

答:
```<code>count = {}
for element in input:
    count[element] = count.get(element,0) + 1

return {key:max(count.values()) - value for (key,value) in count.items() if value != max(count.values())}

</code>```

ContentLicense: CC BY-SA 4.0

Title: Return Missing balancing numbers

Body:
A balanced array would be an array in which each element appears the same number of times.

Given an array with n elements:
return a dictionary with the key as the element and the value as the count of elements needed to balance the given array

Examples

elements = ["a", "b", "abc", "c", "a"]

Expected output: {"b":1, "abc":1, "c":1}

Because there are 2 a, we need 1 more of b, abc, c

Hope that helps


问:
Wait for user input from readline module (Node.Js)
I am creating a module to get experience and shorten some code. I have a piece of code which uses readline in a simplified manner, like var x = arkin.question("How old are you? ");. Readline doesn't wait for the answer. It produces this:

How old are you? undefined

Code:

```<code>const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

exports.question = function(q){

  var response;

  rl.setPrompt(q);
  rl.prompt();
  rl.on('line', (userInput) => {
    response = userInput;
    rl.close();
  });

  rl.on('close', () => {
    return response;
  });
}
</code>```

I call it like this:

```<code>var age = arkin.question("How old are you? ");
console.log(age);
</code>```

I have tried using this code:

```<code>rl.question(q, (userInput) => {
    rl.close;
    response = userInput;
    return response;
});
</code>```

Yet I get the same result. Thanks in advance for your help.

答:
```<code>//global stuff, where we import readline.
//But avoid assigning global vars.
    var age;
    var readline = require('readline'), menu;

//define function
    function whatever() = {

//create readline instance and assign it to menu
    menu = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

//Use the readline.question method, which is what you're looking for.
//It requires a callback function with a variable for the users input.
    menu.question('How old are you? ', function(input) {
        age = input;
    });

    console.log(`You are ${age} years old.`);
}

//Tell node to run the program
whatever();
</code>```

Body:
I am creating a module to get experience and shorten some code. I have a piece of code which uses readline in a simplified manner, like var x = arkin.question("How old are you? ");. Readline doesn't wait for the answer. It produces this:

How old are you? undefined

Code:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

exports.question = function(q){

  var response;

  rl.setPrompt(q);
  rl.prompt();
  rl.on('line', (userInput) => {
    response = userInput;
    rl.close();
  });

  rl.on('close', () => {
    return response;
  });
}

I call it like this:

var age = arkin.question("How old are you? ");
console.log(age);

I have tried using this code:

rl.question(q, (userInput) => {
    rl.close;
    response = userInput;
    return response;
});

Yet I get the same result. Thanks in advance for your help.


问:
copy everything after a string into a different column in R
I have some columns in a data frame that look like this:

```<code>df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                        "DEC S/N, de 05/06/2006",
                         "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)
</code>```

I would like to copy everything after the first ; (MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012) in the column 'act', into the column 'adj'. Ideally, removing the space that would be left at the star of the cut-off string. All other cells, this is, where the strings in column 'act' do not have a ; should be left NA in column 'adj'.

Body:
I have some columns in a data frame that look like this:

df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                        "DEC S/N, de 05/06/2006",
                         "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)

I would like to copy everything after the first ; (MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012) in the column 'act', into the column 'adj'. Ideally, removing the space that would be left at the star of the cut-off string. All other cells, this is, where the strings in column 'act' do not have a ; should be left NA in column 'adj'.

Body:
Using str_match from stringr :

df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                       "DEC S/N, de 05/06/2006",
                       "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)
df %>% mutate(adj = str_match(act, "[^;]*;(.*)")[,2])


问:
Docker daemon is not running
Newbie in this area. I have installed the new version of Docker in my windows PC. I am using windows 10 Pro. I have tried the very basic docker command but it is not working. I have also run the docker as administrator. Getting the below error always

docker: error during connect: Post http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.39/containers/create: open //./pipe/docker_engine: Zugriff verweigert In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

答:
This thread was one of the first that I found, so wanted to compile some of the solutions I've found for various issues.
I am using Windows 11 & a first time docker install.

Issue 1: Docker desktop was 'stopped' and whenever I tried to run a package in the terminal I was getting a long message ending in: This error may also indicate that the docker daemon is not running.

Solution:

Follow the official steps on how to install WSL 2 at https://learn.microsoft.com/en-us/windows/wsl/install

Open PowerShell and run command:
wsl --update

Uninstall Docker.

Delete temporary data:

C:\Users<USER>\AppData\Roaming\Docker

C:\Users\ProgramData\Docker

C:\Users\ProgramData\DockerDesktop

Reinstall Docker, ensure wsl box is ticked during install.

Restart computer.

Run Docker as administrator.

Run PowerShell as administrator.

Run the following command:

& 'C:\Program Files\Docker\Docker\DockerCli.exe' -SwitchDaemon

If this doesn't work, you may need to run the above command one or two more times.

Issue 2: Docker desktop settings check box 'Use the WSL 2 based engine (Windows Home can only run the WSL 2 backend)' was greyed out and unchecked.

Solution:

Open: C:\Users<USER>\AppData\Roaming\Docker\settings.json
Change: "wslEngineEnabled": false to "wslEngineEnabled": true

Reinstall Docker & restart computer. (not sure if necessary.)

Run Docker as administrator.

Run PowerShell as administrator.

Run the following command:

& 'C:\Program Files\Docker\Docker\DockerCli.exe' -SwitchDaemon

If this doesn't work, you may need to run the above command one or two more times.

Title: Docker daemon is not running


问:
CSS problem, 100% width keeps moving out of position
I'm currently working on this website,
http://no-illusions.nl
It's going fine but I found a pretty stupid thing that I can't resolve.

I have an div (wrapper) with an width of 500px and inside I have different div's containing images and text. Now the problem is that the text is dynamic in width, on some parts it could be 200px width and on some pages it could be 350px.

So I put the width on 100% but now the part just floats underneath where I want it!

This is how it should look,
![how it should look][1]

But this is how it looks,

I hope you guys can give me a push in the right direction.

答:
You don't need any width at all for
-tags, as they are block-elements, which are strechted to the maximum width available.

ContentLicense: CC BY-SA 3.0

Body: You don't need any width at all for <p>-tags, as they are block-elements, which are strechted to the maximum width available.


问:
Fill os.Stdin for function that reads from it
How do I fill os.Stdin in my test for a function that reads from it using a scanner?

I request a user command line input via a scanner using following function:

```<code>func userInput() error {
    scanner := bufio.NewScanner(os.Stdin)

    println("What is your name?")
    scanner.Scan()
    username = scanner.Text()

    /* ... */
}
</code>```

Now how do I test this case and simulate a user input?
Following example does not work. Stdin is still empty.

```<code>func TestUserInput(t *testing.T) {
    var file *os.File
    file.Write([]byte("Tom"))
    os.Stdin = file

    err := userInput()
    /* ... */
}
</code>```

答:
Implementation of @icza's easy, preferred way:

Also note that you can refactor userInput() to not read from os.Stdin,
but instead it could receive an io.Reader to read from. This would
make it more robust and a lot easier to test.

In your app you can simply pass os.Stdin to it, and in tests you can
pass any io.Reader to it created / prepared in the tests, e.g. using
strings.NewReader(), bytes.NewBuffer() or bytes.NewBufferString().

hello.go

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
    "io"
)

func userInput(reader io.Reader) error {
    scanner := bufio.NewScanner(reader)
    var username string
    fmt.Println("What is your name?")

    if scanner.Scan() {
        username = scanner.Text()
    }
    if scanner.Err() != nil {
        return scanner.Err()
    }

    fmt.Println("Hello", username)
    return nil
}

func main() {
    userInput(os.Stdin)
}
</code>```

hello_test.go

```<code>package main

import (
    "bytes"
    "io"
    "strings"
    "testing"
)

func TestUserInputWithStringsNewReader(t *testing.T) {
    input := "Tom"
    var reader io.Reader = strings.NewReader(input)

    err := userInput(reader)
    if err != nil {
       t.Errorf("Failed to read from strings.NewReader: %w", err)
    }
}

func TestUserInputWithBytesNewBuffer(t *testing.T) {
    input := "Tom"
    var reader io.Reader = bytes.NewBuffer([]byte(input))

    err := userInput(reader)
    if err != nil {
        t.Errorf("Failed to read from bytes.NewBuffer: %w", err)
    }
}

func TestUserInputWithBytesNewBufferString(t *testing.T) {
    input := "Tom"
    var reader io.Reader = bytes.NewBufferString(input)

    err := userInput(reader)
    if err != nil {
       t.Errorf("Failed to read from bytes.NewBufferString: %w", err)
    }
}
</code>```

Running the program:

go run hello.go

```<code>What is your name?
Tom
Hello Tom
</code>```

Running the test:

go test hello_test.go hello.go -v

```<code>=== RUN   TestUserInputWithStringsNewReader
What is your name?
Hello Tom
--- PASS: TestUserInputWithStringsNewReader (0.00s)
=== RUN   TestUserInputWithBytesNewBuffer
What is your name?
Hello Tom
--- PASS: TestUserInputWithBytesNewBuffer (0.00s)
=== RUN   TestUserInputWithBytesNewBufferString
What is your name?
Hello Tom
--- PASS: TestUserInputWithBytesNewBufferString (0.00s)
PASS
ok      command-line-arguments  0.141s
</code>```

Body:
How do I fill os.Stdin in my test for a function that reads from it using a scanner?

I request a user command line input via a scanner using following function:

func userInput() error {
    scanner := bufio.NewScanner(os.Stdin)

    println("What is your name?")
    scanner.Scan()
    username = scanner.Text()

    /* ... */
}

Now how do I test this case and simulate a user input?
Following example does not work. Stdin is still empty.

func TestUserInput(t *testing.T) {
    var file *os.File
    file.Write([]byte("Tom"))
    os.Stdin = file

    err := userInput()
    /* ... */
}

Body:
Implementation of @icza's easy, preferred way:

Also note that you can refactor userInput() to not read from os.Stdin,
but instead it could receive an io.Reader to read from. This would
make it more robust and a lot easier to test.

In your app you can simply pass os.Stdin to it, and in tests you can
pass any io.Reader to it created / prepared in the tests, e.g. using
strings.NewReader(), bytes.NewBuffer() or bytes.NewBufferString().

hello.go

package main

import (
    "bufio"
    "fmt"
    "os"
    "io"
)

func userInput(reader io.Reader) error {
    scanner := bufio.NewScanner(reader)
    var username string
    fmt.Println("What is your name?")

    if scanner.Scan() {
        username = scanner.Text()
    }
    if scanner.Err() != nil {
        return scanner.Err()
    }

    fmt.Println("Hello", username)
    return nil
}

func main() {
    userInput(os.Stdin)
}

hello_test.go

package main

import (
    "bytes"
    "io"
    "strings"
    "testing"
)

func TestUserInputWithStringsNewReader(t *testing.T) {
    input := "Tom"
    var reader io.Reader = strings.NewReader(input)

    err := userInput(reader)
    if err != nil {
       t.Errorf("Failed to read from strings.NewReader: %w", err)
    }
}

func TestUserInputWithBytesNewBuffer(t *testing.T) {
    input := "Tom"
    var reader io.Reader = bytes.NewBuffer([]byte(input))

    err := userInput(reader)
    if err != nil {
        t.Errorf("Failed to read from bytes.NewBuffer: %w", err)
    }
}

func TestUserInputWithBytesNewBufferString(t *testing.T) {
    input := "Tom"
    var reader io.Reader = bytes.NewBufferString(input)

    err := userInput(reader)
    if err != nil {
       t.Errorf("Failed to read from bytes.NewBufferString: %w", err)
    }
}

Running the program:

go run hello.go

What is your name?
Tom
Hello Tom

Running the test:

go test hello_test.go hello.go -v

=== RUN   TestUserInputWithStringsNewReader
What is your name?
Hello Tom
--- PASS: TestUserInputWithStringsNewReader (0.00s)
=== RUN   TestUserInputWithBytesNewBuffer
What is your name?
Hello Tom
--- PASS: TestUserInputWithBytesNewBuffer (0.00s)
=== RUN   TestUserInputWithBytesNewBufferString
What is your name?
Hello Tom
--- PASS: TestUserInputWithBytesNewBufferString (0.00s)
PASS
ok      command-line-arguments  0.141s


问:
Python fontforge Emoji encoding and colored glyphs
I want to create a .ttf font with python and fontforge which also contains emojis.

my glyphs are .svg files which have a resolution of 512x512 pixels.

I already tried the Following:

```<code>import fontforge
blank = fontforge.font()
blank.save("blank.sfd")
font = fontforge.open("blank.sfd")
glyph = font.createMappedChar("\U0000263A")
glyph.importOutlines("263A.svg")
font.generate("font.ttf")
</code>```

However, I get the following error:

```<code>Traceback (most recent call last):
  File "/home/adrian/dev/font/glyphs/test.py", line 5, in <module>
    glyph = font.createMappedChar("\U0000263A")
ValueError: Glyph name, ☺, not in current encoding
</code>```

I looked into thebblank.sfd and there is a line: "Encoding: ISO8859-1".
I tried to replace the " ISO8859-1" with "UTF-8" or "Univode" but then I get the following error:

```<code>Internal Error: SFD file specifies too few slots for its encoding.
</code>```

How can I solve that?

I tried to use the emoji glyph for letter "A" for first. then font get created and it works.
However, it is just a black circle and face, eyes, smile, blush,... aren't recognizable because it is black instead of Yellow, orange, white, pink,...
In the blank.sfd file is something written about layers:

```<code>Layer: 0 0 "Back" 1
Layer: 1 0 "Fore" 0
</code>```

I guess that I have to change something with the layers to make the colors to take effect but I am not sure and if that's the case I don't know how and how I can assign the layers with elements in the. svg  glyph.
I use the program Inkscape to create the glyps, by the way.

How can I solve these 2 things?

答:
I have stumbled across this wanting a simple character added to my terminal, here's a mix on the question that solves it for me.

For making your own Emoji, you might find this rather difficult with Font Forge in its current state. Just try loading a font like NotoColorEmoji.ttf into FontForge's app and you'll see an error. There is a github issue for it:

https://github.com/fontforge/fontforge/issues/677
https://github.com/fontforge/fontforge/issues/2044

But if the emoji you're trying to make is a single color glyphs like: https://github.com/powerline/powerline, you're in luck.

This script is close to yours but works well:

```<code>import fontforge
blank = fontforge.font()
blank.encoding = "UnicodeBMP"
glyph = blank.createChar(int("F10F", 16))
glyph.importOutlines("logo.svg")
blank.generate("myfont.ttf")
</code>```

Feel free to change the unicode to any sequence in the private use area.

Then copy it to your font directory (if linux)

```<code>sudo cp myfont.ttf /usr/share/fonts/TTF/
</code>```

In a new terminal or reloading display you can: echo -e "\uf10f"

Body:
I want to create a .ttf font with python and fontforge which also contains emojis.

my glyphs are .svg files which have a resolution of 512x512 pixels.

I already tried the Following:

import fontforge
blank = fontforge.font()
blank.save("blank.sfd")
font = fontforge.open("blank.sfd")
glyph = font.createMappedChar("\U0000263A")
glyph.importOutlines("263A.svg")
font.generate("font.ttf")

However, I get the following error:

Traceback (most recent call last):
  File "/home/adrian/dev/font/glyphs/test.py", line 5, in <module>
    glyph = font.createMappedChar("\U0000263A")
ValueError: Glyph name, ☺, not in current encoding

I looked into thebblank.sfd and there is a line: "Encoding: ISO8859-1".
I tried to replace the " ISO8859-1" with "UTF-8" or "Univode" but then I get the following error:

Internal Error: SFD file specifies too few slots for its encoding.

How can I solve that?

I tried to use the emoji glyph for letter "A" for first. then font get created and it works.
However, it is just a black circle and face, eyes, smile, blush,... aren't recognizable because it is black instead of Yellow, orange, white, pink,...
In the blank.sfd file is something written about layers:

Layer: 0 0 "Back" 1
Layer: 1 0 "Fore" 0

I guess that I have to change something with the layers to make the colors to take effect but I am not sure and if that's the case I don't know how and how I can assign the layers with elements in the. svg  glyph.
I use the program Inkscape to create the glyps, by the way.

How can I solve these 2 things?

Body:
I have stumbled across this wanting a simple character added to my terminal, here's a mix on the question that solves it for me.

For making your own Emoji, you might find this rather difficult with Font Forge in its current state. Just try loading a font like NotoColorEmoji.ttf into FontForge's app and you'll see an error. There is a github issue for it:

https://github.com/fontforge/fontforge/issues/677
https://github.com/fontforge/fontforge/issues/2044

But if the emoji you're trying to make is a single color glyphs like: https://github.com/powerline/powerline, you're in luck.

This script is close to yours but works well:

import fontforge
blank = fontforge.font()
blank.encoding = "UnicodeBMP"
glyph = blank.createChar(int("F10F", 16))
glyph.importOutlines("logo.svg")
blank.generate("myfont.ttf")

Feel free to change the unicode to any sequence in the private use area.

Then copy it to your font directory (if linux)

sudo cp myfont.ttf /usr/share/fonts/TTF/

In a new terminal or reloading display you can: echo -e "\uf10f"


问:
can someone please fix this this termux module
Hi I have been using this termux instagram bot for a very long time and it is very effective too. But suddenly a month ago this bot wouldn't open so can any one please fix this?
git clone https://github.com/sanjidtk/sbot
enter image description here

enter image description here

enter image description here

答: Try to delete the repo and perform git clone and run again. I'm not sure if it's going back to normal. I am not good at node.js part so I can't diagnose the whole issue, you should alert that to the creator and he/she will give you the answer</p>


问:
Zend redirect() is not working with AJAX request?
For example I have an action in Controller.

```<code>public function redirectnowAction() {
   $this->_redirect( '/module/controller/action' );
}
</code>```

When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.

JS code for AJAX

```<code>jQuery('.AjaxLink').live( 'click', function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html( snippets[id] );
        }
    });
});
</code>```

How to redirect to action after AJAX request ?

Thanks

答:
When you use a redirect, you send a header to the user's browser to fetch content at the new location.

AJAX requests are not usually setup to handle such redirects. They simply initiate a request, and return the response.

The best-case solution is to reorganize your code so a redirect is not necessary. If you cannot eliminate the redirect, you must update your Javascript to recognize the redirect status (HTTP 301, for example) and initiate a new request.

Body:
For example I have an action in Controller.

public function redirectnowAction() {
   $this->_redirect( '/module/controller/action' );
}

When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.

JS code for AJAX

jQuery('.AjaxLink').live( 'click', function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html( snippets[id] );
        }
    });
});

How to redirect to action after AJAX request ?

Thanks


问:
Count number of objects in JSON array on a URL in swift5
I have a JSON array at url = https://api.github.com/users/greenrobot/starred .

I want to count how many objects are there in that array using swift. I don't want data present, I just want count of it.

答:
Assuming you downloaded the contents of that URL into a variable data of type Data:

```<code>if let object = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String: AnyHashable]] {
    let count = object[0].keys.count
}
</code>```

Body:
Assuming you downloaded the contents of that URL into a variable data of type Data:

if let object = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String: AnyHashable]] {
    let count = object[0].keys.count
}


问:
Errors with writing score in python
I am currently making a simple turtle game and when I try to write a score, it does not show even though it is above the background layer (turtle.write is at the bottom and the code has been shortend).

import turtle
score = 0
score = 0
px = 0
py = 260

s = turtle.Screen()
s.setup(width=600, height=500)
s.bgcolor("black")

pen = turtle.Turtle()
pen.color("white")
pen.penup()
pen.goto(0, 260)

cr = turtle.Turtle()
cr.penup()
cr.shape("square")
cr.color("white")
cr.shapesize(stretch_len=4, stretch_wid=0.01)
cr.goto(x,y)

cr2 = turtle.Turtle()
cr2.penup()
cr2.shape("square")
cr2.color("white")
cr2.shapesize(stretch_len=0.01, stretch_wid=4)
cr2.goto(x,y)
while True:
    s.update()

    if cr.xcor() != cr2.ycor():
        cr.setx(cr2.xcor())
    if cr.ycor() != cr2.xcor():
        cr.sety(cr2.ycor())
    pen.write("hello!")```

答:
Your code example is unrunnable.  Regardless, let's consider these three lines:

```<code>s.setup(width=600, height=500)
pen.goto(0, 260)
pen.write("hello!")
</code>```

The first line sets the range of visible Y coordinates to -250 to +250.  The second line moves the pen to a Y coordinate of 260, off the top of the screen.  The third line writes text that's off the top of the screen.  Change the Y coordinate in the second line from 250 to 240, putting that turtle back onto the screen, and you'll see the output of the write().

Title: Errors with writing score in python

Body:
Your code example is unrunnable.  Regardless, let's consider these three lines:

s.setup(width=600, height=500)
pen.goto(0, 260)
pen.write("hello!")

The first line sets the range of visible Y coordinates to -250 to +250.  The second line moves the pen to a Y coordinate of 260, off the top of the screen.  The third line writes text that's off the top of the screen.  Change the Y coordinate in the second line from 250 to 240, putting that turtle back onto the screen, and you'll see the output of the write().


问:
How to use variables in dot notation like square bracket notation with variable depth
How can I access different JSON objects in JavaScript by a variable containing the attribute's path?

```<code>var item = {
              "car": {
                 "manufacturer": "Ford",
                 "model": "Taunus"
                 "surface": {
                     "color": "silver",
                     "type": "metallic"
                 }
                 "built (year)": "1975"
           };

let foo = "model";
let bar = "surface.color";

consloe.log("Model: " + item[foo]);          // Output: "Taunus"
console.log("Surface color:" + item[bar]);   // Output: "undefined", Desired output "silver"
</code>```

This notation represents only one hierarchic level per set of brackets, of course. Is there an easy elegant way to access several levels with only one labeling variable like "one.two" and "one.two.three"?

答:
You can create a function that will split the string with . (dot) as the delimiter into an array of strings, and use them to traverse the object in a reducer function.

```<code>const item = {
  "car": {
    "manufacturer": "Ford",
    "model": "Taunus",
    "surface": {
        "color": "silver",
        "type": "metallic"
    },
    "built (year)": "1975"
  }
}

const foo = "car.model";
const bar = "car.surface.color";

function get(path) {
  const parts = path.split(".");
  return parts.reduce((obj, part) => obj[part], item);
}

get(foo); // should return "Taunus"
get(bar); // should return "silver"
</code>```

Body:
How can I access different JSON objects in JavaScript by a variable containing the attribute's path?

var item = {
              "car": {
                 "manufacturer": "Ford",
                 "model": "Taunus"
                 "surface": {
                     "color": "silver",
                     "type": "metallic"
                 }
                 "built (year)": "1975"
           };

let foo = "model";
let bar = "surface.color";

consloe.log("Model: " + item[foo]);          // Output: "Taunus"
console.log("Surface color:" + item[bar]);   // Output: "undefined", Desired output "silver"

This notation represents only one hierarchic level per set of brackets, of course. Is there an easy elegant way to access several levels with only one labeling variable like "one.two" and "one.two.three"?

Body:
You can create a function that will split the string with . (dot) as the delimiter into an array of strings, and use them to traverse the object in a reducer function.

const item = {
  "car": {
    "manufacturer": "Ford",
    "model": "Taunus",
    "surface": {
        "color": "silver",
        "type": "metallic"
    },
    "built (year)": "1975"
  }
}

const foo = "car.model";
const bar = "car.surface.color";

function get(path) {
  const parts = path.split(".");
  return parts.reduce((obj, part) => obj[part], item);
}

get(foo); // should return "Taunus"
get(bar); // should return "silver"


问:
Is this expression statement in a C programming exam question undefined behavior?
In a C programming exam question, I found this:

int a, b=0, x=4, y=5;
a=((a=x%y?b+1:y--)&&(x-=y))||(y-=6);
```
<p>Is this expression UB?</p>
<p>I would say no, because of the sequence point (SP) between logic operators and between expressions of <code>?:</code>. So, to my understanding, the horrible hack would be evaluated correctly as:</p>
```      x%y                             this gives 4 (exp is true)
    a=    b+1                         this assigns 1 to a and we have a SP (exp is true)
              y--                     this is not evaluated
                     x-=y             this assigns -1 to x and we have a SP (exp is true)
                              y-=6    this is not evaluated
a=                                    this assigns the result of the || operator to a (1)
```

Finally a=1, x=-1, nothing else is changed. Any mistake?

答:
```<code>#include <stdio.h>

int main() {
    int a, b=0, x=4, y=5;
    a=((a=x%y?b+1:y--)&&(x-=y))||(y-=6);
    printf("a=%i\nb=%i\nx=%i\ny=%i\n", a,b,x,y);
    return 0;
}
</code>```

OUTPUT:

```<code>a=1
b=0
x=-1
y=5
</code>```

So I think you are right about everything but I do not think it counts as undefined behavior.

Body:
In a C programming exam question, I found this:

int a, b=0, x=4, y=5;
a=((a=x%y?b+1:y--)&&(x-=y))||(y-=6);

Is this expression UB?

I would say no, because of the sequence point (SP) between logic operators and between expressions of ?:. So, to my understanding, the horrible hack would be evaluated correctly as:

      x%y                             this gives 4 (exp is true)
    a=    b+1                         this assigns 1 to a and we have a SP (exp is true)
              y--                     this is not evaluated
                     x-=y             this assigns -1 to x and we have a SP (exp is true)
                              y-=6    this is not evaluated
a=                                    this assigns the result of the || operator to a (1)

Finally a=1, x=-1, nothing else is changed. Any mistake?

Body:
#include <stdio.h>

int main() {
    int a, b=0, x=4, y=5;
    a=((a=x%y?b+1:y--)&&(x-=y))||(y-=6);
    printf("a=%i\nb=%i\nx=%i\ny=%i\n", a,b,x,y);
    return 0;
}

OUTPUT:

a=1
b=0
x=-1
y=5

So I think you are right about everything but I do not think it counts as undefined behavior.


问:
Get height and width from a phaser canvas
So I use phaser.io but I want to print an array so I create it in my page html.

To put the height and width of my array I need to know the height and width of my canvas.

So I just should just do :

```<code>$('canvas').height();
</code>```

Mission complete.

But not there is a trap my canvas look like this :

```<code><canvas width="1261" height="1101" style="display: block; touch-action: none; user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1059px; height: 925px; cursor: inherit; margin-left: 1px; margin-right: 0px; margin-top: 0px;"></canvas>
</code>```

And each time it return me the value from height not the one from the style.

So I try other way :

```<code>$('canvas').css('height');
$('canvas').[0].style.height;
$('canvas')[0].style.cssText;
</code>```

But I always get the wrong result

what is super weird is that when I do :

```<code>console.log($('canvas')[0].style)
</code>```

I see exactly the result I want inside the element 'height' and 'cssText'. I put a part of the result here :

```<code> 0:"display"
    1:"touch-action"
    2:"user-select"
    3:"-webkit-tap-highlight-color"
    4:"width"
    5:"height"
    6:"margin-left"
    7:"margin-right"
    8:"margin-top"
    ...
    cssText:"display: block; touch-action: none; user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1059px; height: 925px; margin-left: 1px; margin-right: 0px; margin-top: 0px;"
    ...
    height:"925px"
    ...
</code>```

Someone can tell me why? and give me a solution can be nice also.

======= EDIT =======

I get some news when I do $('canvas').height() on a click on an element it's work. Actualy I can deal with it but I still don't understand why when I do :

```<code>console.log($('canvas')[0].style.cssText);
console.log($('canvas').height());
</code>```

Just the one after the other I get different result. Certainly a question of loading time ... but still don't sound good to me.

window.onload = function() {

 var Level = {
  preload: function()
  {
   console.log("toto");
  },
        create: function()
  {
   console.log($('canvas').height());
   console.log($('canvas')[0].style.cssText);

   this.scale.pageAlignHorizontally = true;
      this.scale.pageAlignVertically = true;
      this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            this.scale.refresh();
  }
    }
 const SAFE_ZONE_WIDTH=640;
 const SAFE_ZONE_HEIGHT=1101;

 var w = window.innerWidth ;
 var h = window.innerHeight ;
 var aspectRatioDevice = w/h;

 var aspectRatioSafeZone = SAFE_ZONE_WIDTH / SAFE_ZONE_HEIGHT;
 var extraWidth = 0, extraHeight = 0, offsetWidth = 0;
 if (aspectRatioSafeZone < aspectRatioDevice)
 {
  // have to add game pixels horizontally in order to fill the device screen
  extraWidth = aspectRatioDevice * SAFE_ZONE_HEIGHT - SAFE_ZONE_WIDTH;
  offsetWidth = extraWidth/2;
 }
 else
 {
  // have to add game pixels vertically
  extraHeight = SAFE_ZONE_WIDTH / aspectRatioDevice - SAFE_ZONE_HEIGHT;
 }

 var game = new Phaser.Game( SAFE_ZONE_WIDTH + extraWidth, SAFE_ZONE_HEIGHT + extraHeight, Phaser.CANVAS, 'game_div');

 game.state.add('Level', Level);
 game.state.start('Level');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
<head>

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, height = device-height, user-scalable=no, target-densitydpi = device-dpi" />
<title>niuniu</title>
<script>
    screen.orientation.lock('portrait');
</script>
<script src="https://github.com/photonstorm/phaser-ce/releases/download/v2.9.4/phaser.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

</body>
</html></code>```

答:
In Phaser (v3) you have access to game.canvas, which is the canvas (element) Phaser is running on, so:

const game = new Phaser.Game({ ... });
console.log(game.canvas.width, game.canvas.height);
```

Body:
So I use phaser.io but I want to print an array so I create it in my page html.

To put the height and width of my array I need to know the height and width of my canvas.

So I just should just do :

$('canvas').height();

Mission complete.

But not there is a trap my canvas look like this :

<canvas width="1261" height="1101" style="display: block; touch-action: none; user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1059px; height: 925px; cursor: inherit; margin-left: 1px; margin-right: 0px; margin-top: 0px;"></canvas>

And each time it return me the value from height not the one from the style.

So I try other way :

$('canvas').css('height');
$('canvas').[0].style.height;
$('canvas')[0].style.cssText;

But I always get the wrong result

what is super weird is that when I do :

console.log($('canvas')[0].style)

I see exactly the result I want inside the element 'height' and 'cssText'. I put a part of the result here :

 0:"display"
    1:"touch-action"
    2:"user-select"
    3:"-webkit-tap-highlight-color"
    4:"width"
    5:"height"
    6:"margin-left"
    7:"margin-right"
    8:"margin-top"
    ...
    cssText:"display: block; touch-action: none; user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1059px; height: 925px; margin-left: 1px; margin-right: 0px; margin-top: 0px;"
    ...
    height:"925px"
    ...

Someone can tell me why? and give me a solution can be nice also.

======= EDIT =======

I get some news when I do $('canvas').height() on a click on an element it's work. Actualy I can deal with it but I still don't understand why when I do :

console.log($('canvas')[0].style.cssText);
console.log($('canvas').height());

Just the one after the other I get different result. Certainly a question of loading time ... but still don't sound good to me.

window.onload = function() {

 var Level = {
  preload: function()
  {
   console.log("toto");
  },
        create: function()
  {
   console.log($('canvas').height());
   console.log($('canvas')[0].style.cssText);

   this.scale.pageAlignHorizontally = true;
      this.scale.pageAlignVertically = true;
      this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            this.scale.refresh();
  }
    }
 const SAFE_ZONE_WIDTH=640;
 const SAFE_ZONE_HEIGHT=1101;

 var w = window.innerWidth ;
 var h = window.innerHeight ;
 var aspectRatioDevice = w/h;

 var aspectRatioSafeZone = SAFE_ZONE_WIDTH / SAFE_ZONE_HEIGHT;
 var extraWidth = 0, extraHeight = 0, offsetWidth = 0;
 if (aspectRatioSafeZone < aspectRatioDevice)
 {
  // have to add game pixels horizontally in order to fill the device screen
  extraWidth = aspectRatioDevice * SAFE_ZONE_HEIGHT - SAFE_ZONE_WIDTH;
  offsetWidth = extraWidth/2;
 }
 else
 {
  // have to add game pixels vertically
  extraHeight = SAFE_ZONE_WIDTH / aspectRatioDevice - SAFE_ZONE_HEIGHT;
 }

 var game = new Phaser.Game( SAFE_ZONE_WIDTH + extraWidth, SAFE_ZONE_HEIGHT + extraHeight, Phaser.CANVAS, 'game_div');

 game.state.add('Level', Level);
 game.state.start('Level');
}

<!DOCTYPE HTML>

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, height = device-height, user-scalable=no, target-densitydpi = device-dpi" />
<title>niuniu</title>

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


问:
How do you update a component again straight after an update in react
So i'm trying to make a bar turn green then afterwards go back to its original color of black but it seems like it takes the later line as what it updates.</p>
```<code>
const [color, setColor] = useState("black")
const bubbleSort = async () => {
    const sleep = ms => new Promise(res => setTimeout(res, ms));
      let len = arr.length;
      for (let i = 0; i < len; i++) {
          for (let j = 0; j < len; j++) {
              setCurrentIndex(j)
              console.log(j)
              console.log(currentIndex)
              if (arr[j] > arr[j + 1]) {
                  setColor("green")
                  console.log(color)
                  document.getElementById(`bar${j + 1}`).style.backgroundColor = color
                  let tmp = arr[j];
                  arr[j] = arr[j + 1];
                  arr[j + 1] = tmp;
                  setArr([...arr])
              }
              setColor("black")

              await sleep(200)
          }

      }

</code>```

答:
This seems like it could be easily done with an useEffect hook.

something like this...

```<code>const FooComponent = () => {
  const [color, setColor] = useState("black")

  useEffect(()=> {
    if(color === "green") {
      setTimeout(function(){
        setColor("black");
    }, 3000);
    }
  }, [color, setColor])

  return <div onClick={() => setColor("green")}> HI </div>

}
</code>```

So the useEffect works like that. Every time color changes it will run that func.

In our example, when you click the div the color will be set to green and it will run the useEffect hook that will wait for 3 seconds and than set the color back to black,

Body:
So i'm trying to make a bar turn green then afterwards go back to its original color of black but it seems like it takes the later line as what it updates.

const [color, setColor] = useState("black")
const bubbleSort = async () => {
    const sleep = ms => new Promise(res => setTimeout(res, ms));
      let len = arr.length;
      for (let i = 0; i < len; i++) {
          for (let j = 0; j < len; j++) {
              setCurrentIndex(j)
              console.log(j)
              console.log(currentIndex)
              if (arr[j] > arr[j + 1]) {
                  setColor("green")
                  console.log(color)
                  document.getElementById(`bar${j + 1}`).style.backgroundColor = color
                  let tmp = arr[j];
                  arr[j] = arr[j + 1];
                  arr[j + 1] = tmp;
                  setArr([...arr])
              }
              setColor("black")

              await sleep(200)
          }

      }

Body:
This seems like it could be easily done with an useEffect hook.

something like this...

const FooComponent = () => {
  const [color, setColor] = useState("black")

  useEffect(()=> {
    if(color === "green") {
      setTimeout(function(){
        setColor("black");
    }, 3000);
    }
  }, [color, setColor])

  return <div onClick={() => setColor("green")}> HI </div>

}

So the useEffect works like that. Every time color changes it will run that func.

In our example, when you click the div the color will be set to green and it will run the useEffect hook that will wait for 3 seconds and than set the color back to black,


问:
Powershell - Find computers with a specific username logged in
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

```<code>Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }
</code>```

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

答:
Do you have the ability to read the remote registry on these computers?

If so:

Get a list for registry keys from \\{Computername}\HKU

Filter out all that DO NOT end with '_Classes'

```<code>HKEY_USERS\.DEFAULT
HKEY_USERS\S-1-5-19
HKEY_USERS\S-1-5-20
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1001
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005_Classes
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-500
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-26824
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976_Classes
HKEY_USERS\S-1-5-18
</code>```

becomes

```<code>HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005_Classes
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976_Classes
</code>```

From the now filtered list remove '_Classes' from the end of the keys.

```<code>HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005_Classes
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976_Classes
</code>```

becomes

```<code>HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976
</code>```

If any remain, then try to read the "USERNAME" value from the "Volatile Environment" key from each.

```<code>HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005\Volatile Environment
{Throws error, was just a ghost of past login - not real}
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976\Volatile Environment
    USERNAME    REG_SZ    {UserName}
</code>```

Been doing this from BATCH language with REG.EXE and don't believe I've ever seen 2 names come back from step 4 above.  If no keys remains after step 3, or all attempts to read USERNAME fails in step 4, then no one is logged on.  If one name comes back, I guess it could be a ghost left over from a system crash, but in theory, it should be the user logged on.

I've seen PSLoggedOn \{ComputerName} fail to give correct info, so I think this is simply a very hard thing to do since Windows will crash, or have other problems, and leaves ghost fragments from past users.

Sorry I don't PowerShell code, still fairly new to PowerShell and haven't nose dived into the registry that far yet.

If I really needed to know for a fact who is logged on or not, I would investigate seeing if there is a way to get a script to run every 2 minutes while the user is logged in, and have the script save a UserName/DateTime stamp at the end of a log file in \Users\Public every time it ran.  But I would have to want it bad to do that much work.

Body:
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

Body:
Do you have the ability to read the remote registry on these computers?

If so:

Get a list for registry keys from \\{Computername}\HKU

Filter out all that DO NOT end with '_Classes'

HKEY_USERS\.DEFAULT
HKEY_USERS\S-1-5-19
HKEY_USERS\S-1-5-20
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1001
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005_Classes
HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-500
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-26824
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976_Classes
HKEY_USERS\S-1-5-18

becomes

HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005_Classes
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976_Classes

From the now filtered list remove '_Classes' from the end of the keys.

HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005_Classes
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976_Classes

becomes

HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976

If any remain, then try to read the "USERNAME" value from the "Volatile Environment" key from each.

HKEY_USERS\S-1-5-21-4155237567-380904213-1424831347-1005\Volatile Environment
{Throws error, was just a ghost of past login - not real}
HKEY_USERS\S-1-5-21-515967899-1938372697-839532595-3976\Volatile Environment
    USERNAME    REG_SZ    {UserName}

Been doing this from BATCH language with REG.EXE and don't believe I've ever seen 2 names come back from step 4 above.  If no keys remains after step 3, or all attempts to read USERNAME fails in step 4, then no one is logged on.  If one name comes back, I guess it could be a ghost left over from a system crash, but in theory, it should be the user logged on.

I've seen PSLoggedOn \{ComputerName} fail to give correct info, so I think this is simply a very hard thing to do since Windows will crash, or have other problems, and leaves ghost fragments from past users.

Sorry I don't PowerShell code, still fairly new to PowerShell and haven't nose dived into the registry that far yet.

If I really needed to know for a fact who is logged on or not, I would investigate seeing if there is a way to get a script to run every 2 minutes while the user is logged in, and have the script save a UserName/DateTime stamp at the end of a log file in \Users\Public every time it ran.  But I would have to want it bad to do that much work.


问:
Issue laying out components with React and Flexbox
Here is a puzzling problem I am facing with the layout of some components in a web app.

First of all here is the source code MyCompo.js:

```<code>import React from "react";
import tblClp from './images/WoodSquare.jpg';
import dwnArwClp from './images/DownArrow.png';
import upArwClp from './images/UpArrow.png';
import './MyCompo.css';

class MyCompo extends React.Component {
  render() {
    const elements = [...Array(3).keys()]
    const items = []

    for (const [index, value] of elements.entries()) {
      items.push(<SquareUnit index={index}/>)
    }

    return (
      <div>
        {items}
      </div>
    )
  }
}

class SquareUnit extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>
        <div id={this.props.index}>
                    <div><img src={tblClp} width='130' height='109'/>
            <div className="overlay down">
                <img src={dwnArwClp} width='40' height='40'/>
                </div>
            <div className="overlay up">
                <img src={upArwClp} width='40' height='40'/>
              </div>
                    </div>
        </div>
      </React.Fragment>
    )
  }
}

export default MyCompo;
</code>```

And here is the style sheet MyCompo.css:

```<code>body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.overlay {
    position: relative;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    transition: .3s ease;
    background-color: transparent;
    bottom: 0;
    right: 0;
}

.down {
    top: -24%;
    left: 3%;
}

.up {
    top: -76%;
    left: 65%;
}

.container {
    position: relative;
    width: 100%;
    max-width: 400px;
}
</code>```

I run my app for development using this command in the terminal:

```<code>$ npm start
</code>```

And this is what I see in the browser after adjusting the .down {...} and .up {...} blocks inside MyCompo.css and saving the file.

As one can see MyCompo is made of three wooden square blocks, each one having two arrows (up and down) overlayed on top of it.

The above screenshot is what I get as well as what I expect.

But here comes the problem and my question:

When I refresh the browser window, the display changes to the following:

which is no longer what I expect.

What is wrong in my code MyCompo.js or MyCompo.css for this to happen?

答:
It looks like the .container class is never implemented on the parent div, so it does not have the display: relative applied to it, forcing the arrows outside of it. My guess is that this should fix it:

```<code><React.Fragment>
    <div id={this.props.index}>
        <div className="container">
            <img src={tblClp} width='130' height='109'/>
            <div className="overlay down">
                <img src={dwnArwClp} width='40' height='40'/>
            </div>
            <div className="overlay up">
                <img src={upArwClp} width='40' height='40'/>
            </div>
        </div>
    </div>
</React.Fragment>
</code>```

Body:
Here is a puzzling problem I am facing with the layout of some components in a web app.

First of all here is the source code MyCompo.js:

import React from "react";
import tblClp from './images/WoodSquare.jpg';
import dwnArwClp from './images/DownArrow.png';
import upArwClp from './images/UpArrow.png';
import './MyCompo.css';

class MyCompo extends React.Component {
  render() {
    const elements = [...Array(3).keys()]
    const items = []

    for (const [index, value] of elements.entries()) {
      items.push(<SquareUnit index={index}/>)
    }

    return (

        {items}

    )
  }
}

class SquareUnit extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>

      </React.Fragment>
    )
  }
}

export default MyCompo;

And here is the style sheet MyCompo.css:

body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.overlay {
    position: relative;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    transition: .3s ease;
    background-color: transparent;
    bottom: 0;
    right: 0;
}

.down {
    top: -24%;
    left: 3%;
}

.up {
    top: -76%;
    left: 65%;
}

.container {
    position: relative;
    width: 100%;
    max-width: 400px;
}

I run my app for development using this command in the terminal:

$ npm start

And this is what I see in the browser after adjusting the .down {...} and .up {...} blocks inside MyCompo.css and saving the file.

As one can see MyCompo is made of three wooden square blocks, each one having two arrows (up and down) overlayed on top of it.

The above screenshot is what I get as well as what I expect.

But here comes the problem and my question:

When I refresh the browser window, the display changes to the following:

which is no longer what I expect.

What is wrong in my code MyCompo.js or MyCompo.css for this to happen?

Body:
It looks like the .container class is never implemented on the parent div, so it does not have the display: relative applied to it, forcing the arrows outside of it. My guess is that this should fix it:

<React.Fragment>
    <div id={this.props.index}>
        <div className="container">
            <img src={tblClp} width='130' height='109'/>
            <div className="overlay down">
                <img src={dwnArwClp} width='40' height='40'/>
            </div>
            <div className="overlay up">
                <img src={upArwClp} width='40' height='40'/>
            </div>
        </div>
    </div>
</React.Fragment>


问:
Discord bot not detecting when I deafen
Basically, I want my discord bot to move me to AFK as soon as I deafen but it does nothing with the code I have. I have tried using console.log on the if statement but still nothing.

Code:

client.on("voiceStateUpdate", (oldState, newState) => {
    let memchange = newState.member;
    if (memchange.selfDeaf) {
        memchange.setChannel(afkchannelid);
    }
});
```

答:
Did you add the GUILD_VOICE_STATES intent ?

const client = new Client({ intents: ['GUILD_VOICE_STATES'] });
```

Title: Discord bot not detecting when I deafen


问:
What do I add to requirements.txt for font awesome (font-awesome)
SO yeah I'm pretty new to this I used font-awesome for some icons (free version) but after i tried to deploy it to heroku it got some errors, I highly suspect that it is due to requirements.txt, can anyone tell me what I should write in there? I tried font-awesome-free==16.0 but that didnt really work...</p>

答:
Kind of this requirements.txt. You can create

```<code>Flask==0.8
Jinja2==2.6
Werkzeug==0.8.3
certifi==0.0.8
chardet==1.0.1
distribute==0.6.24
gunicorn==0.14.2
requests==0.11.1
</code>```

So that it could fetch or default will work. This is an example

Body:
Kind of this requirements.txt. You can create

Flask==0.8
Jinja2==2.6
Werkzeug==0.8.3
certifi==0.0.8
chardet==1.0.1
distribute==0.6.24
gunicorn==0.14.2
requests==0.11.1

So that it could fetch or default will work. This is an example


问:
copy everything after a string into a different column in R
I have some columns in a data frame that look like this:

```<code>df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                        "DEC S/N, de 05/06/2006",
                         "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)
</code>```

I would like to copy everything after the first ; (MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012) in the column 'act', into the column 'adj'. Ideally, removing the space that would be left at the star of the cut-off string. All other cells, this is, where the strings in column 'act' do not have a ; should be left NA in column 'adj'.

Body:
I have some columns in a data frame that look like this:

df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                        "DEC S/N, de 05/06/2006",
                         "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)

I would like to copy everything after the first ; (MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012) in the column 'act', into the column 'adj'. Ideally, removing the space that would be left at the star of the cut-off string. All other cells, this is, where the strings in column 'act' do not have a ; should be left NA in column 'adj'.

Body:
Using stringr::str_extract -

df$adj <- stringr::str_extract(df$act, '(?<=;\\s)(.*)')
df$adj
#[1] NA   NA    "MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"


问:
Hibernate: ManyToMany with REST Endpoint

The Context

I'm currently exploring JPA and am having trouble saving a ManyToMany relationship. I get the data to be saved as JSON, as in the following example:

```<code>{
"oid":"ghi",
"id":9,
"name":"Test 3",
"permissions":[],
"roles":[{"id":2,"name":"MyRole 2","permissions":["PERM1","PERM2"]}]
}
</code>```

The roles should be reused because they already exist in the database.

I can create new roles and edit existing ones. Creating and editing users without roles also works. However, when I try to create a new user with a role, I get the following error message:

Caused by: org.hibernate.TransientObjectException: object references
an unsaved transient instance - save the transient instance before
flushing: ***.entity.Role

If I want to assign roles to an existing user without roles, I get the following message:

Caused by: java.lang.NullPointerException: Cannot invoke
"java.lang.Integer.intValue()" because "this.id" is null  at
***.entity.Role.hashCode(Role.java:74)

And if I want to remove or edit the roles from an existing user, I get the following message:

Caused by: javax.persistence.PersistenceException:
org.hibernate.exception.ConstraintViolationException: could not
execute statement Caused by: org.postgresql.util.PSQLException:
FEHLER: doppelter Schlüsselwert verletzt Unique-Constraint
»user_oid_key«

My Questions

I notice that I have no reference to the user in the role. Does this always have to be present with "mappedBy", even if I don't need it?

My expectation is that when I create or update a user, the program only updates the references to the roles - not the roles. Do I need additional code for the transformation of the roles?

Or what can be the reason why Hibernate fails completely as soon as I want to change objects in a many-to-many relationship? I am thankful for every hint.

Code

```<code>@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(unique = true)
    @Size(max = 255)
    private String oid;

    @Size(max = 50)
    private String name;

    @Convert(converter = StringSetConverter.class)
    private Set<String> permissions;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "role_id"))
    @OrderBy("name")
    private Set<Role> roles;
    ...
}

@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Size(max = 50)
    private String name;

    @Convert(converter = StringSetConverter.class)
    private Set<String> permissions;
    ...
}
</code>```

The processing code is kept very simple. I parse the JSON object and call em.merge() to update and em.persist() to create.

And with PostgreSQL I created the following tables:

```<code>CREATE TABLE "user" (
    id  SERIAL PRIMARY KEY,
    oid VARCHAR(255) UNIQUE,
    name VARCHAR(50),
    permissions TEXT
);

CREATE TABLE role (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50),
    permissions TEXT
);

CREATE TABLE user_role (
    user_id INTEGER REFERENCES "user"(id),
    role_id INTEGER REFERENCES role(id),
    PRIMARY KEY (user_id, role_id)
);
</code>```

答:
After further research I came across the following post:
JPA persist new entity with relationship to existing entity

Consequently, the roles were not known to JPA. I assumed that JPA would create a relationship based on the ID of the roles during the merge process. But it seems that I had to do this myself:

```<code>public User update(User user) {
    Set<Role> roles = new HashSet<Role>();
    for(Role role : user.getRoles()) {
        Role r = em.find(Role.class, role.getId());
        roles.add(r != null ? r : role);
    }
    user.setRoles(roles);
    user = em.merge(user);
    return user;
}
</code>```

Body:
The Context

I'm currently exploring JPA and am having trouble saving a ManyToMany relationship. I get the data to be saved as JSON, as in the following example:

{
"oid":"ghi",
"id":9,
"name":"Test 3",
"permissions":[],
"roles":[{"id":2,"name":"MyRole 2","permissions":["PERM1","PERM2"]}]
}

The roles should be reused because they already exist in the database.

I can create new roles and edit existing ones. Creating and editing users without roles also works. However, when I try to create a new user with a role, I get the following error message:

Caused by: org.hibernate.TransientObjectException: object references
an unsaved transient instance - save the transient instance before
flushing: ***.entity.Role

If I want to assign roles to an existing user without roles, I get the following message:

Caused by: java.lang.NullPointerException: Cannot invoke
"java.lang.Integer.intValue()" because "this.id" is null  at
***.entity.Role.hashCode(Role.java:74)

And if I want to remove or edit the roles from an existing user, I get the following message:

Caused by: javax.persistence.PersistenceException:
org.hibernate.exception.ConstraintViolationException: could not
execute statement Caused by: org.postgresql.util.PSQLException:
FEHLER: doppelter Schlüsselwert verletzt Unique-Constraint
»user_oid_key«

My Questions

I notice that I have no reference to the user in the role. Does this always have to be present with "mappedBy", even if I don't need it?

My expectation is that when I create or update a user, the program only updates the references to the roles - not the roles. Do I need additional code for the transformation of the roles?

Or what can be the reason why Hibernate fails completely as soon as I want to change objects in a many-to-many relationship? I am thankful for every hint.

Code

@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(unique = true)
    @Size(max = 255)
    private String oid;

    @Size(max = 50)
    private String name;

    @Convert(converter = StringSetConverter.class)
    private Set<String> permissions;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "role_id"))
    @OrderBy("name")
    private Set<Role> roles;
    ...
}

@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Size(max = 50)
    private String name;

    @Convert(converter = StringSetConverter.class)
    private Set<String> permissions;
    ...
}

The processing code is kept very simple. I parse the JSON object and call em.merge() to update and em.persist() to create.

And with PostgreSQL I created the following tables:

CREATE TABLE "user" (
    id  SERIAL PRIMARY KEY,
    oid VARCHAR(255) UNIQUE,
    name VARCHAR(50),
    permissions TEXT
);

CREATE TABLE role (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50),
    permissions TEXT
);

CREATE TABLE user_role (
    user_id INTEGER REFERENCES "user"(id),
    role_id INTEGER REFERENCES role(id),
    PRIMARY KEY (user_id, role_id)
);

Body:
After further research I came across the following post:
JPA persist new entity with relationship to existing entity

Consequently, the roles were not known to JPA. I assumed that JPA would create a relationship based on the ID of the roles during the merge process. But it seems that I had to do this myself:

public User update(User user) {
    Set<Role> roles = new HashSet<Role>();
    for(Role role : user.getRoles()) {
        Role r = em.find(Role.class, role.getId());
        roles.add(r != null ? r : role);
    }
    user.setRoles(roles);
    user = em.merge(user);
    return user;
}


问:
how to loop over values in servlets and display them in them table?
I am writing a servlet calculator using doPost method of servlet container.

```<code> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //show result page

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>SIMPLE CALCULATOR<br><br><br></head>");
        out.println("<body>");
        out.println("<form method = 'post' action = 'calc'>");
        out.println("enter the first number:<br>");
        out.println("<input type = 'text' name='number1'><br><br>");
        out.println("enter the second number:<br>");
        out.println("<input type = 'text' name='number2'><br><br>");
        out.println("enter the operation:<br><br>");
        out.println("<input type ='radio' name = 'op' value = '+'>add<br>");
        out.println("<input type = 'radio' name = 'op' value = '-'>sub<br>");
        out.println("<input type = 'radio' name = 'op' value = '*'>mul<br>");
        out.println("<input type = 'radio' name = 'op' value = '/'>div<br><br>");
        out.println("<input type = 'submit' name = 'result' value = 'submit'><br>");
        out.println("</body>");
        out.println("</html>");
        int a1= Integer.parseInt(request.getParameter("number1"));
        int a2= Integer.parseInt(request.getParameter("number2"));
        String operation = request.getParameter("op");
        int result = 0;
        if(operation.equals("+"))
        {
            result = a1 + a2;
            out.println("The result of " + a1 + " " + operation + " "+ a2 + " = "+ result);
        }
        if(operation.equals("-"))
        {
            result = a1 - a2;
            out.println("The result of " + a1 + " " + operation + " " + a2 + " = "+ result);
        }
        if(operation.equals("*"))
        {
            result = a1 * a2;
            out.println("The result of " + a1 + " " + operation + " " + a2 + " = "+ result);
        }if(operation.equals("/"))
        {
            result = a1 / a2;
            out.println("The result of " + a1 + operation + a2 + " = "+ result);
        }

        out.println("<table border=1>");
        out.println("<tr>");
        out.println("<th>first</th>");
        out.println("<th>operation</th>");
        out.println("<th>second</th>");
        out.println("<th>result</th>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td>" + a1 + "</td>");
        out.println("<td>" + operation + "</td>");
        out.println("<td>" + a2 + "</td>");
        out.println("<td>" + result + "</td>");
        out.println("</tr>");
        out.println("</table>");

        out.flush();
    }
</code>```

I wanted to display the values and operations and results everytime I do calculation and click the submit button. What I am now seeing is that only the first calculation values are displayed and when I do the second one It changes the previous one and displays itself.
Expected output is

I am now seeing

Anyone has any help?

答:
My solution would be to use a list of strings to store the history.  If you want a better solution, you could write a class that has first, second, and operator so that you can retrieve each property.  I store the list in the session so that it can be accessed by the JSP page.  I'm just writing a minimal solution.  It's up to you to rewrite it to meet your requirements.

JSP page

```<code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<form action="ComputeServlet" method="post">
<input type="text" name="firstNumber" size="5">
<select name="operator">
  <option value="+">+</option>
  <option value="+">-</option>
  <option value="+">*</option>
  <option value="+">/</option>
</select>
<input type="text" name="secondNumber" size="5">
<input type="submit" name="submit" value="submit">

<c:forEach var="problem" items="${history}">
  <p>${problem}</p>
</c:forEach>
<input type="submit" name="clear" value="clear">
</form>
</code>```

Servlet

```<code>protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

  if (request.getParameter("clear")!=null){
    List<String> history = (List<String>) request.getSession().getAttribute("history");
    if (history == null){
      history = new ArrayList<>();
      request.getSession().setAttribute("history", history);
    } else {
      history.clear();
    }
  } else if (request.getParameter("submit")!=null){
     int first = Integer.parseInt(request.getParameter("firstNumber"));
     int second = Integer.parseInt(request.getParameter("secondNumber"));
     String op = request.getParameter("operator");
     int result = 0;
     switch(op){
       case "+": result = first+second; break;
       case "*": result = first*second; break;
       case "/": result = first/second; break;
       case "-": result = first-second; break;
      }
    List<String> history = (List<String>) request.getSession().getAttribute("history");
    if (history == null){
      history = new ArrayList<>();
      request.getSession().setAttribute("history", history);
    }
    history.add("" + first + op + second + "=" + result);
  }
  getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
</code>```

Output

```<code><form action="ComputeServlet" method="post">
<input type="text" name="firstNumber" size="5">
<select name="operator">
  <option value="+">+</option>
  <option value="+">-</option>
  <option value="+">*</option>
  <option value="+">/</option>
</select>
<input type="text" name="secondNumber" size="5">
<input type="submit" name="submit" value="submit">

  <p>4+5=9</p>
  <p>2+6=8</p>
  <p>3+2=5</p>
  <p>3+2=5</p>

<input type="submit" name="clear" value="clear">
</form>
</code>```

Body:
I am writing a servlet calculator using doPost method of servlet container.

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //show result page

        PrintWriter out = response.getWriter();
        out.println("");
        out.println("SIMPLE CALCULATOR

");
        out.println("");
        out.println("<form method = 'post' action = 'calc'>");
        out.println("enter the first number:
");
        out.println("<input type = 'text' name='number1'>

");
        out.println("enter the second number:
");
        out.println("<input type = 'text' name='number2'>

");
        out.println("enter the operation:

");
        out.println("<input type ='radio' name = 'op' value = '+'>add
");
        out.println("<input type = 'radio' name = 'op' value = '-'>sub
");
        out.println("<input type = 'radio' name = 'op' value = '*'>mul
");
        out.println("<input type = 'radio' name = 'op' value = '/'>div

");
        out.println("<input type = 'submit' name = 'result' value = 'submit'>
");
        out.println("");
        out.println("");
        int a1= Integer.parseInt(request.getParameter("number1"));
        int a2= Integer.parseInt(request.getParameter("number2"));
        String operation = request.getParameter("op");
        int result = 0;
        if(operation.equals("+"))
        {
            result = a1 + a2;
            out.println("The result of " + a1 + " " + operation + " "+ a2 + " = "+ result);
        }
        if(operation.equals("-"))
        {
            result = a1 - a2;
            out.println("The result of " + a1 + " " + operation + " " + a2 + " = "+ result);
        }
        if(operation.equals("*"))
        {
            result = a1 * a2;
            out.println("The result of " + a1 + " " + operation + " " + a2 + " = "+ result);
        }if(operation.equals("/"))
        {
            result = a1 / a2;
            out.println("The result of " + a1 + operation + a2 + " = "+ result);
        }

        out.println("
");
        out.println("
");
        out.println("first	");
        out.println("operation	");
        out.println("second	");
        out.println("result	");
        out.println("
");
        out.println("
");
        out.println("" + a1 + "	");
        out.println("" + operation + "	");
        out.println("" + a2 + "	");
        out.println("" + result + "	");
        out.println("
");
        out.println("
");

        out.flush();
    }

I wanted to display the values and operations and results everytime I do calculation and click the submit button. What I am now seeing is that only the first calculation values are displayed and when I do the second one It changes the previous one and displays itself.
Expected output is

I am now seeing

Anyone has any help?

Body:
My solution would be to use a list of strings to store the history.  If you want a better solution, you could write a class that has first, second, and operator so that you can retrieve each property.  I store the list in the session so that it can be accessed by the JSP page.  I'm just writing a minimal solution.  It's up to you to rewrite it to meet your requirements.

JSP page

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<form action="ComputeServlet" method="post">
<input type="text" name="firstNumber" size="5">
<select name="operator">
  <option value="+">+</option>
  <option value="+">-</option>
  <option value="+">*</option>
  <option value="+">/</option>
</select>
<input type="text" name="secondNumber" size="5">
<input type="submit" name="submit" value="submit">

<c:forEach var="problem" items="${history}">
  <p>${problem}</p>
</c:forEach>
<input type="submit" name="clear" value="clear">
</form>

Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

  if (request.getParameter("clear")!=null){
    List<String> history = (List<String>) request.getSession().getAttribute("history");
    if (history == null){
      history = new ArrayList<>();
      request.getSession().setAttribute("history", history);
    } else {
      history.clear();
    }
  } else if (request.getParameter("submit")!=null){
     int first = Integer.parseInt(request.getParameter("firstNumber"));
     int second = Integer.parseInt(request.getParameter("secondNumber"));
     String op = request.getParameter("operator");
     int result = 0;
     switch(op){
       case "+": result = first+second; break;
       case "*": result = first*second; break;
       case "/": result = first/second; break;
       case "-": result = first-second; break;
      }
    List<String> history = (List<String>) request.getSession().getAttribute("history");
    if (history == null){
      history = new ArrayList<>();
      request.getSession().setAttribute("history", history);
    }
    history.add("" + first + op + second + "=" + result);
  }
  getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}

Output

<form action="ComputeServlet" method="post">
<input type="text" name="firstNumber" size="5">
<select name="operator">
  <option value="+">+</option>
  <option value="+">-</option>
  <option value="+">*</option>
  <option value="+">/</option>
</select>
<input type="text" name="secondNumber" size="5">
<input type="submit" name="submit" value="submit">

  <p>4+5=9</p>
  <p>2+6=8</p>
  <p>3+2=5</p>
  <p>3+2=5</p>

<input type="submit" name="clear" value="clear">
</form>


问:
Failed to register application "/". Error description: The process cannot access the file because it is being used by another process. (0x80070020)
If you are not able to run your application due to the following error:

Failed to register application "/". Error description: The process cannot access the file because it is being used by another process. (0x80070020)

答:
Open a command prompt and run the following command:

netsh interface ipv4 show excludedportrange protocol=tcp

Here you will see the list of used ports in a range e.g. from (start port) 10000 to (end port) 11000 etc. etc.

What you want to do is to go to the settings of your project and set a port that is not falling under any range of the listed ones in the CMD after running netsh interface command.


问:
Combine row values into character vector by condition
I have a data.frame where values are repeated in col1.

```<code>col1 <- c("A", "A", "B", "B", "C")
col2 <- c(1995, 1997, 1999, 2000, 2005)

df <- data.frame(col1, col2)
</code>```

I want to combine values in col2 that correspond to the same letter in col1 into one cell, so that col2 shows a range of values for a particular letter in col1. I do this by splitting the data.frame by col1, applying fun, and binding the split data.frames back together.

```<code>library(tidyverse)

split_df <- split(df, df$col1)

fun <- function(df) {

  if (length(unique(df$col2)) > 1) {

    df$col2 <- paste(min(df$col2),
                     max(df$col2),
                     sep = "-")

    df <- distinct(df)

  }

  return(df)
}

split_df <- lapply(split_df, fun)

df <- do.call(rbind, split_df)
</code>```

This works, but I am wondering if there is a more intuitive or more efficient solution?

答:
Base R way using aggregate -

```<code>aggregate(col2~col1, df, function(x)  paste0(unique(range(x)), collapse = '-'))

#  col1      col2
#1    A 1995-1997
#2    B 1999-2000
#3    C      2005
</code>```

Same can also be written with dplyr -

```<code>library(dplyr)

df %>%
  group_by(col1) %>%
  summarise(col2 = paste0(unique(range(col2)), collapse = '-'))
</code>```

Body:
I have a data.frame where values are repeated in col1.

col1 <- c("A", "A", "B", "B", "C")
col2 <- c(1995, 1997, 1999, 2000, 2005)

df <- data.frame(col1, col2)

I want to combine values in col2 that correspond to the same letter in col1 into one cell, so that col2 shows a range of values for a particular letter in col1. I do this by splitting the data.frame by col1, applying fun, and binding the split data.frames back together.

library(tidyverse)

split_df <- split(df, df$col1)

fun <- function(df) {

  if (length(unique(df$col2)) > 1) {

    df$col2 <- paste(min(df$col2),
                     max(df$col2),
                     sep = "-")

    df <- distinct(df)

  }

  return(df)
}

split_df <- lapply(split_df, fun)

df <- do.call(rbind, split_df)

This works, but I am wondering if there is a more intuitive or more efficient solution?

Body:
Base R way using aggregate -

aggregate(col2~col1, df, function(x)  paste0(unique(range(x)), collapse = '-'))

#  col1      col2
#1    A 1995-1997
#2    B 1999-2000
#3    C      2005

Same can also be written with dplyr -

library(dplyr)

df %>%
  group_by(col1) %>%
  summarise(col2 = paste0(unique(range(col2)), collapse = '-'))


问:
How to output ARM V8 assembly from LLVM IR?
I have this C file:

```<code>int mult() {
  int a =5;
  int b = 3;
  int c = a * b;
  return c;
}
</code>```

I compile it to LLVM IR like this:

```<code>$ clang -emit-llvm -S multiply.c -o multiply.ll
</code>```

I then compile it to various x86 assemblies like this:

```<code>$ llc --filetype asm -o multiply.apple.s --aarch64-neon-syntax=apple multiply.ll
$ llc --filetype asm -o multiply.intel.s --x86-asm-syntax=intel multiply.ll
</code>```

How do I output ARM V8 assembly? Is there any way to convert a C file to output ARM V8 assembly, even without LLVM IR if LLVM IR can't do it? I don't see it in the llc docs for example.

答:
llc -march=aarch64 multiply.ll -o multiply.s will do it.

However, you shouldn't actually do that because the translation from C to LLVM IR is target-dependent. Simple things will work and complex programs will break in seemingly impossible ways.

Instead, go directly from C to your target with clang -target arm64. As your programs get more complicated, such as using system headers, you'll need to have an SDK matching the target platform installed. Even #include <stdlib.h> is very different on two platforms.

Body:
I have this C file:

int mult() {
  int a =5;
  int b = 3;
  int c = a * b;
  return c;
}

I compile it to LLVM IR like this:

$ clang -emit-llvm -S multiply.c -o multiply.ll

I then compile it to various x86 assemblies like this:

$ llc --filetype asm -o multiply.apple.s --aarch64-neon-syntax=apple multiply.ll
$ llc --filetype asm -o multiply.intel.s --x86-asm-syntax=intel multiply.ll

How do I output ARM V8 assembly? Is there any way to convert a C file to output ARM V8 assembly, even without LLVM IR if LLVM IR can't do it? I don't see it in the llc docs for example.


问:
Asking for input again with do while loop in c
I am trying to have the user type in a number between 1 and 8 to print out stuff on screen (height), if the number is lower than 1 or higher than 8 I would like for the program to prompt again for an input instead of it quitting out and say "invalid". I know I have to set it up with do on top and when on the bottom in C, my question is how would I go about it when I have 2 possible outcomes, i.e. too low or too high?</p>
```<code>do {
    int height = get_int(Height: ");
    if (height < 1)
        ~ ~printf("invalid");
    else if (height > 8)
        ~ ~printf("invalid");
} when(???????)

printf("valid")
</code>```

答:
I hope this helps you.

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

int main() {
    int num;
    do {
        printf("Enter 0 to quit\n");
        printf("Print Enter number between 1 and 8\n");
        scanf("%d",&num);
        if (num > 8) {
            printf("Number to high\n");
        } else if (num < 0) {
            printf("Number to low\n");
        }

        if (num == 0) {
            printf("You quit the program goodby\n");
        } else {
            printf("Number within range\n");
        }
    } while(num != -0);

    return 0;
}
```

Body:
I am trying to have the user type in a number between 1 and 8 to print out stuff on screen (height), if the number is lower than 1 or higher than 8 I would like for the program to prompt again for an input instead of it quitting out and say "invalid". I know I have to set it up with do on top and when on the bottom in C, my question is how would I go about it when I have 2 possible outcomes, i.e. too low or too high?

do {
    int height = get_int(Height: ");
    if (height < 1)
        ~ ~printf("invalid");
    else if (height > 8)
        ~ ~printf("invalid");
} when(???????)

printf("valid")


问:
Reading a file in python and sending contents to two different variables
I am trying to read the file and put the two sequences (ie Spar and Sbay) into two variables seq1 and seq2. So far I only know how to pass everything to one sequence by using this code.

```<code>filename = 'AQY2.fasta'
readfile = open(filename, 'r')
seq1 = ''
seq2 = ''
for line in readfile.readlines():
     if ( line[0] == '>' ):
         header = line[1:]
     else:
         seq1 = seq1 + line

readfile.close()
print(seq1)
</code>```

Can anyone help me to read the two sequences into seq1 and seq2?

The image contains two sequences

答:
I am using two vaiable matchSpar and matchSbay to read the file and seq a dictionary to store the corresponding result.

if matchSpar is set to True then lines added append to '>Spar' key in seq dictionary if matchSbay is set to True then lines added append to '>Sbay' key in seq dictionary.

```<code>filename = 'AQY2.fasta'
readfile = open(filename, 'r')
seq= {
        '>Spar' : "",
        '>Sbay' : ""
        }
matchSpar = False
matchSbay = False
lines = []
for line in readfile.readlines():
    line = line.replace('\n', '')
    if line == '>Spar':
        matchSpar = True
        matchSbay = False

    if line == '>Sbay':
        matchSpar = False
        matchSbay = True

    if matchSpar :
        seq[">Spar"] += line+"\n"
    if matchSbay :
        seq[">Sbay"] += line+"\n"

readfile.close()

print(seq['>Spar'])
print(seq['>Sbay'])
</code>```

Its recommended to use with keyword to file handling in python :

```<code>filename = 'AQY2.fasta'
seq= {
        '>Spar' : "",
        '>Sbay' : ""
        }
matchSpar = False
matchSbay = False

with open(filename, 'r') as readfile:
 for line in readfile.readlines():
    if line == '>Spar\n':
        matchSpar = True
        matchSbay = False

    if line == '>Sbay\n':
        matchSpar = False
        matchSbay = True

    if matchSpar :
        seq[">Spar"] += line
    if matchSbay :
        seq[">Sbay"] += line

print(seq['>Spar'])
print(seq['>Sbay'])
</code>```

Body:
I am trying to read the file and put the two sequences (ie Spar and Sbay) into two variables seq1 and seq2. So far I only know how to pass everything to one sequence by using this code.

filename = 'AQY2.fasta'
readfile = open(filename, 'r')
seq1 = ''
seq2 = ''
for line in readfile.readlines():
     if ( line[0] == '>' ):
         header = line[1:]
     else:
         seq1 = seq1 + line

readfile.close()
print(seq1)

Can anyone help me to read the two sequences into seq1 and seq2?

The image contains two sequences

Body:
I am using two vaiable matchSpar and matchSbay to read the file and seq a dictionary to store the corresponding result.

if matchSpar is set to True then lines added append to '>Spar' key in seq dictionary if matchSbay is set to True then lines added append to '>Sbay' key in seq dictionary.

filename = 'AQY2.fasta'
readfile = open(filename, 'r')
seq= {
        '>Spar' : "",
        '>Sbay' : ""
        }
matchSpar = False
matchSbay = False
lines = []
for line in readfile.readlines():
    line = line.replace('\n', '')
    if line == '>Spar':
        matchSpar = True
        matchSbay = False

    if line == '>Sbay':
        matchSpar = False
        matchSbay = True

    if matchSpar :
        seq[">Spar"] += line+"\n"
    if matchSbay :
        seq[">Sbay"] += line+"\n"

readfile.close()

print(seq['>Spar'])
print(seq['>Sbay'])

Its recommended to use with keyword to file handling in python :

filename = 'AQY2.fasta'
seq= {
        '>Spar' : "",
        '>Sbay' : ""
        }
matchSpar = False
matchSbay = False

with open(filename, 'r') as readfile:
 for line in readfile.readlines():
    if line == '>Spar\n':
        matchSpar = True
        matchSbay = False

    if line == '>Sbay\n':
        matchSpar = False
        matchSbay = True

    if matchSpar :
        seq[">Spar"] += line
    if matchSbay :
        seq[">Sbay"] += line

print(seq['>Spar'])
print(seq['>Sbay'])


问:
Optional for showAndWait
My question is when the showAndWait's output is null? Because in my program it has two ok and cancel buttons and neither of the cancel and close buttons gives null output.

```<code> dialog.showAndWait().ifPresent(buttonType -> {
        System.out.println(buttonType);
}
</code>```

when I press the close button(X) and the cancel button the output is(not null):

```<code>ButtonType [text=Cancel, buttonData=CANCEL_CLOSE]
</code>```

答:
Note that Dialog#showAndWait() returns an Optional and will never return null. However, the returned Optional may be empty. From reading through the documentation, this will occur in the following cases:

The result converter returns null.

There is only one non-cancel button and the dialog is closed "abnormally" (e.g. the X button is clicked).

But note this will give you an empty Optional only if the result converter returns null (or there's no result converter) and the result property contains null.

Here's an example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class App extends Application {

  @Override
  public void start(Stage primaryStage) {
    var btn = new Button("Show dialog...");
    btn.setOnAction(
        e -> {
          Dialog<Object> dialog = new Dialog<>();
          dialog.setContentText("Empty Optional test.");
          dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
          dialog
              .showAndWait()
              .ifPresentOrElse(System.out::println, () -> System.out.println("NO RESULT"));
        });
    var scene = new Scene(new StackPane(btn), 600, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}
```
<p>Running the above, showing the dialog, and then clicking the <kbd>X</kbd> button will result in the following output:</p>
<pre class="lang-none prettyprint-override"><code>NO RESULT
</code>```

In other words, the Optional was empty.

You mention your tests include cancel buttons. That's why you see a non-empty Optional, because by default the result will be the first matching cancel button when the dialog is closed "abnormally". See the "Dialog Closing Rules" section of Dialog's Javadoc for more information.

Title: Optional for showAndWait

Body:
My question is when the showAndWait's output is null? Because in my program it has two ok and cancel buttons and neither of the cancel and close buttons gives null output.

 dialog.showAndWait().ifPresent(buttonType -> {
        System.out.println(buttonType);
}

when I press the close button(X) and the cancel button the output is(not null):

ButtonType [text=Cancel, buttonData=CANCEL_CLOSE]

Body:
Note that Dialog#showAndWait() returns an Optional and will never return null. However, the returned Optional may be empty. From reading through the documentation, this will occur in the following cases:

The result converter returns null.

There is only one non-cancel button and the dialog is closed "abnormally" (e.g. the X button is clicked).

But note this will give you an empty Optional only if the result converter returns null (or there's no result converter) and the result property contains null.

Here's an example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class App extends Application {

  @Override
  public void start(Stage primaryStage) {
    var btn = new Button("Show dialog...");
    btn.setOnAction(
        e -> {
          Dialog<Object> dialog = new Dialog<>();
          dialog.setContentText("Empty Optional test.");
          dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
          dialog
              .showAndWait()
              .ifPresentOrElse(System.out::println, () -> System.out.println("NO RESULT"));
        });
    var scene = new Scene(new StackPane(btn), 600, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

Running the above, showing the dialog, and then clicking the X button will result in the following output:

NO RESULT

In other words, the Optional was empty.

You mention your tests include cancel buttons. That's why you see a non-empty Optional, because by default the result will be the first matching cancel button when the dialog is closed "abnormally". See the "Dialog Closing Rules" section of Dialog's Javadoc for more information.