问:
GO generate incorrect UTF-8 chars like Ã¶
Ik building an GO application where I want to output a cvs string from a buffer out via the http server.

I'm putting it into the csv buffer:

```<code>var buffer bytes.Buffer
resp := csv.NewWriter(&buffer)
resp.Write("Schröder")
</code>```

The output it via the http server:

```<code>resp.Flush()
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Write([]byte(buffer.String()))
</code>```

When I then open my url a csv file is download en opened by Excel. In that excelsheet the field value is converted to "SchrÃ¶der".

Any idee, i'm already a week stuk on this item?

答:
The problem is not in Go but in Excel. The information that the data are encoded in UTF-8 is lost when saving the file, since there is no such thing as an encoding attribute on saved files.

Thus Excel will just see the plan data and has no information about the encoding. There are several tricks to make Excel do the right guess, like placing the proper byte order mark (BOM) at start of the file. See Is it possible to force Excel recognize UTF-8 CSV files automatically?. But just specifying charset=utf-8 within the HTTP Content-type header will not help since Excel does not get this information.

Body:
Ik building an GO application where I want to output a cvs string from a buffer out via the http server.

I'm putting it into the csv buffer:

var buffer bytes.Buffer
resp := csv.NewWriter(&buffer)
resp.Write("Schröder")

The output it via the http server:

resp.Flush()
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Write([]byte(buffer.String()))

When I then open my url a csv file is download en opened by Excel. In that excelsheet the field value is converted to "SchrÃ¶der".

Any idee, i'm already a week stuk on this item?


来源: stackexchange

问:
CosmosDB: Can I reduce the consumption of RUs when I split the document (in case of updating)?
I have a question regarding CosmosDB and how to deal with the costs and RUs. Lets say I have JSON document which is around 100KB big. Now when I want to update a property and use an upsert the cosmos will do a replace which is essentially a delete and create which will result in relatively high consumption of RU right?

My first question is, can I reduce the amount of RUs for updating when I split the file into smaller parts?  Let's say 10x 10KB documents. Because then a smaller document has to be replaced and it needs less CPU etc.

So this would be the case for upserts. But now there is a game changer for ComsosDB called partial update.

How would it be in this case? Would smaller files lead to a decrease in RU consumption? Because in the background cosmos has to parse the file and insert the new property. Bigger file more to parse more consumption of RU?

My last question is: Will the split into more files lead to higher consumption of RUs because I have to do 10 requests instead of one?

答:
I'm going to preface my answer with the comment that anything performance related is something that users need to test themselves because the benefits or trade-offs can vary widely. There is however some general guidance around this.

In scenarios where you have very large documents with frequent updates on a small number of properties, it is often better to shred that document with one document that has the frequently updated properties and another that has the static properties. Smaller documents consume less RU/s to update and also reduce the load on the client and network payload.

Partial updates provides zero benefit over Update or Upsert for RU/s regardless of whether you shred the document or not. The service still needs to patch and merge the entire document. It will only reduce CPU consumption and network payload due to the smaller amount of data.

ContentLicense: CC BY-SA 4.0


问:
How to record video with VLC in my C# app
I am making a streaming app  in c# and I have embedded the vlc player using vlc.dotnet.

How can I add the feature to allow the user to record the livestreaming with a press of a button for example.

And how can I view the seek bar as the livestreaming goes on?

Thank you!

答:
Vlc.DotNet is archived, and you're expected to use LibVLCSharp instead.

Recording "on-the-fly" is not yet possible with libvlc (and thus not with LibVLCSharp nor Vlc.DotNet). It is a feature that is only possible with VLC, but you can start a second stream and pass it the same recording options as the CLI.

Have a look at the "How do I?" section

To view the "seek bar", you have to implement it yourself, you have properties that give you the time, duration and position plus events that lets you know when Time/Position changed.


问:
Cypress - get value that is inside a component (into a variable)
I'm a new developer and I am trying to build a certain test using cypress. the client has a dynamic grid, and I'd like to see which row in the grid contains the data I want. I cannot change the HTML file.

At the moment I am trying to iterate over all rows using each() cypress command. So I have two questions:

is this a correct approach?

assuming it is correct, how do I get the value out of the component? for example, how do I get the value of "aaaaaaaa" out of here (and into a variable):
html structure

thanks!

答:
There are a number of approaches you can take, but I think my preferred one is to store the variable in Cypress environment variable. In the following, I get the element, then use a .then() statement to get the text of the element (with the JQuery function, .text()), and store it in a Cypress environment variable (via Cypress.env()).

describe('tests', () => {
  it('test', () => {
    cy.get('some-element').then(($el) => {
      Cypress.env('myVar', $el.text());
    })
    ... // some code
    // When needing the variable, reference it by Cypress.env('myVar');
   });

  afterEach(() => {
    // after each test, clear the variable
    Cypress.env('myVar', null)
  });
});

```


问:
How to grab specific details of device from result file using Python

I have more than 100 Apple Devices in my office. I want the details of particular device I want

I used PyAtv a python module to scan the devices which are on my network.

So I created a script which gives me the result like this when called.

```<code>rexter@rexter-pc:~$ python3 scan.py

Scan Results
========================================
       Name: Himanshu Gupta’s Mac mini (intel)
   Model/SW: Macmini8,1, Unknown OS
    Address: 192.168.3.243
        MAC: F0:18:98:EF:D2:E6
 Deep Sleep: False
Identifiers:
 - F0:18:98:EF:D2:E6
 - F01898EFD2E6
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Home Cinema
   Model/SW: Apple TV 4K, tvOS 14.4 build 18K802
    Address: 192.168.3.19
        MAC: C8:D0:83:B0:70:C7
 Deep Sleep: False
Identifiers:
 - C8:D0:83:B0:70:C7
 - 257B0C06-0227-4E42-AEEA-3C2C42B3E829
 - C8D083B070C7
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: MRP, Port: 49153, Credentials: None, Requires Password: False, Password: None, Pairing: Optional
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Pluto - GROUND FLOOR
   Model/SW: ShairportSync, Unknown OS
    Address: 172.17.100.55
        MAC: None
 Deep Sleep: False
Identifiers:
 - E4BB83B4A641
Services:
 - Protocol: RAOP, Port: 8901, Credentials: None, Requires Password: False, Password: None, Pairing: NotNeeded

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
</code>```

But I want to get the results of specific device

```<code>EXAMPLE >>> python3 scan.py 2424

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
</code>```

I tried a lot but the challenge I face is Multiple Services and Identifiers in the results

Any help is appreciated! Thanks!

答:
You either pass one or more identifiers (preferably all of them) to scan:

# Single identifier
confs = await pyatv.scan(loop, identifier="id")

# Multiple identifiers
confs = await pyatv.scan(loop, identifier={"id1", "id2", "id3"})
```
<p>It's the same identifiers you see when running <code>atvremote scan</code>.</p>
<p>Alternatively you can pass the IP address via hosts (does not work if the device is on another network though).</p>
<pre class="lang-py prettyprint-override"><code>confs = await pyatv.scan(loop, hosts=["10.0.0.6"])
</code>```

It's all described in the documentation here as well:

https://pyatv.dev/development/scan_pair_and_connect/#scan

Body:
I have more than 100 Apple Devices in my office. I want the details of particular device I want

I used PyAtv a python module to scan the devices which are on my network.

So I created a script which gives me the result like this when called.

rexter@rexter-pc:~$ python3 scan.py

Scan Results
========================================
       Name: Himanshu Gupta’s Mac mini (intel)
   Model/SW: Macmini8,1, Unknown OS
    Address: 192.168.3.243
        MAC: F0:18:98:EF:D2:E6
 Deep Sleep: False
Identifiers:
 - F0:18:98:EF:D2:E6
 - F01898EFD2E6
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Home Cinema
   Model/SW: Apple TV 4K, tvOS 14.4 build 18K802
    Address: 192.168.3.19
        MAC: C8:D0:83:B0:70:C7
 Deep Sleep: False
Identifiers:
 - C8:D0:83:B0:70:C7
 - 257B0C06-0227-4E42-AEEA-3C2C42B3E829
 - C8D083B070C7
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: MRP, Port: 49153, Credentials: None, Requires Password: False, Password: None, Pairing: Optional
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Pluto - GROUND FLOOR
   Model/SW: ShairportSync, Unknown OS
    Address: 172.17.100.55
        MAC: None
 Deep Sleep: False
Identifiers:
 - E4BB83B4A641
Services:
 - Protocol: RAOP, Port: 8901, Credentials: None, Requires Password: False, Password: None, Pairing: NotNeeded

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

But I want to get the results of specific device

EXAMPLE >>> python3 scan.py 2424

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

I tried a lot but the challenge I face is Multiple Services and Identifiers in the results

Any help is appreciated! Thanks!

Body:
You either pass one or more identifiers (preferably all of them) to scan:

# Single identifier
confs = await pyatv.scan(loop, identifier="id")

# Multiple identifiers
confs = await pyatv.scan(loop, identifier={"id1", "id2", "id3"})

It's the same identifiers you see when running atvremote scan.

Alternatively you can pass the IP address via hosts (does not work if the device is on another network though).

confs = await pyatv.scan(loop, hosts=["10.0.0.6"])

It's all described in the documentation here as well:

https://pyatv.dev/development/scan_pair_and_connect/#scan


问:
Need help creating a Regex
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

答:
The regex:

```<code>^20\d\d[01]\d[123]\d*$
</code>```

Starts with 20, then 2 of any digits, then 0 or 1, then any digits, then 1, 2 or 3, then only digits or nothing.

ContentLicense: CC BY-SA 3.0

Title: Need help creating a Regex

Body:
The regex:

^20\d\d[01]\d[123]\d*$

Starts with 20, then 2 of any digits, then 0 or 1, then any digits, then 1, 2 or 3, then only digits or nothing.


问:
Apply border radius to Typeahead react js
i  have the below code

```<code>                <Typeahead
                    id="ty"
                    onChange={setSelected}
                    options={options}
                    placeholder="Business type ..."
                    selected={selected}
                    style={{height:"50px",borderRadius:"200px"}}
                />
</code>```

when I want to style the input box with border radius it is not working, how can I do that?

答: It's impossible to change the border-radius with borderRadius. because when you add style in Typeahead component, it will apply to only top parent element. but original border radius is applied in input box. you have to add custom css for this

Body:
i  have the below code

                <Typeahead
                    id="ty"
                    onChange={setSelected}
                    options={options}
                    placeholder="Business type ..."
                    selected={selected}
                    style={{height:"50px",borderRadius:"200px"}}
                />

when I want to style the input box with border radius it is not working, how can I do that?


问:
I need the url in the ajax script to be a variable from a php file but I don't know how to do this
The top section has the variables and forms.  The program calls an html page depending on who logs in.  I need to be able to pull the page based on login information.

I pull the page number from the url when the page is called.  I need to use that page number in the ajax part of the program at the bottom to pull the data off the right page and put it in the chatbox.

Right now I can't pull the right page.  I am having a problem setting a variable in the ajax url:

I tried using "" but it will load the chatbox inside the chatbox as an image.

```<code>    <?php
    if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
    $_SESSION['name'] =
    stripslashes(htmlspecialchars($_POST['name']));
    }
    else{
    echo '<span class="error">Please type in a name</span>';
    }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Chat - Customer Module</title>
    <link type="text/css" rel="stylesheet" href="style1.css" />
    </head>
    <body>

    <?php
    if(!isset($_SESSION['name'])){
    loginForm();
    }
    else{
    ?>
    <div id="wrapper">
    <div id="menu">
    <p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?>
    </b></p>
    <p class="logout"><a id="exit" href="#">Exit Chat</a></p>
    <div style="clear:both"></div>
    </div>
    <div id="chatbox"><?php
    if(file_exists($log) && filesize($log) > 0){
        $handle = fopen($log, "r");
        $contents = fread($handle, filesize($log));
        fclose($handle);
        echo $contents;
    }
     else{
        if(!isset($log));
        $contents = 'Welcome!';
        file_put_contents($log, $contents);
        echo $contents;
    }
    ?>
    </div>

    <form name="message" action="">
    <input name="usermsg" type="text" id="usermsg" size="63" />
    <input name="submitmsg" type="submit"  id="submitmsg"
    value="Send" />
    </form>
    <br />
    <form action="upload.php" method="post" enctype="multipart/form-
     data">
    Select image to upload:
    <input type="file" name="fileToUpload" />
    <input type="submit" value="Upload Image" name="submit" />
    </form>
    </div>
    <script type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js">
    </script>
    <script type="text/javascript">
    // jQuery Document
    $(document).ready(function(){
        //If user submits the form
    $("#submitmsg").click(function(){
    var clientmsg = $("#usermsg").val();
    $.post("post.php", {text: clientmsg});
    $("#usermsg").attr("value", "");
    return false;
    });

    //Load the file containing the chat log
    function loadLog(){
       var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;

    $.ajax({
    url: "chat/9999.html",

    cache: false,
    success: function(html){
    $("#chatbox").html(html); //Insert chat log into the #chatbox div
    var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    if(newscrollHeight > oldscrollHeight){
    $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal');
        //Autoscroll to bottom of div
                }
            },
        });
    }
    setInterval (loadLog, 2500);    //Reload file every 2.5 seconds

     //If user wants to end session
    $("#exit").click(function(){
        var exit = confirm("Are you sure you want to end the
            session?");
    if(exit==true){window.location = 'index.php?logout=true';}
    });
    });
    </script>
</code>```

I have updated to give you more code.  I tried using the "" but the form isn't acting right.  It keeps loading the form inside the form again.

I need the "chat/9999.html" to be a variable so it can bring up one of a few pages.

答:
If your ajax code is in a JS file, could use a hidden input to make the URL available, but not visible on the page, then query the value of the input from JS.</p>
```<code>// index.php
<?php
// Get URL
$url = 'chat/9999.html';
?>

<input id="url-from-php" type="hidden" value="<?= $url ?>">
</code>```
```<code>// script.js
$.ajax({
  url: document.getElementById('url-from-php').value,

  cache: false,
  success: function (html) {
    $("#chatbox").html(html); //Insert chat log into the #chatbox div
    var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    if (newscrollHeight > oldscrollHeight) {
      $("#chatbox").animate({ scrollTop: newscrollHeight }, "normal"); //Autoscroll to bottom  of div
    }
  },
});
</code>```

Body:
The top section has the variables and forms.  The program calls an html page depending on who logs in.  I need to be able to pull the page based on login information.

I pull the page number from the url when the page is called.  I need to use that page number in the ajax part of the program at the bottom to pull the data off the right page and put it in the chatbox.

Right now I can't pull the right page.  I am having a problem setting a variable in the ajax url:

I tried using "" but it will load the chatbox inside the chatbox as an image.

    <?php
    if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
    $_SESSION['name'] =
    stripslashes(htmlspecialchars($_POST['name']));
    }
    else{
    echo 'Please type in a name';
    }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Chat - Customer Module</title>
    <link type="text/css" rel="stylesheet" href="style1.css" />

    <?php
    if(!isset($_SESSION['name'])){
    loginForm();
    }
    else{
    ?>

Welcome, <?php echo $_SESSION['name']; ?>

Exit Chat

<?php
    if(file_exists($log) && filesize($log) > 0){
        $handle = fopen($log, "r");
        $contents = fread($handle, filesize($log));
        fclose($handle);
        echo $contents;
    }
     else{
        if(!isset($log));
        $contents = 'Welcome!';
        file_put_contents($log, $contents);
        echo $contents;
    }
    ?>

    <form name="message" action="">
    <input name="usermsg" type="text" id="usermsg" size="63" />
    <input name="submitmsg" type="submit"  id="submitmsg"
    value="Send" />
    </form>

    <form action="upload.php" method="post" enctype="multipart/form-
     data">
    Select image to upload:
    <input type="file" name="fileToUpload" />
    <input type="submit" value="Upload Image" name="submit" />
    </form>

I have updated to give you more code.  I tried using the "" but the form isn't acting right.  It keeps loading the form inside the form again.

I need the "chat/9999.html" to be a variable so it can bring up one of a few pages.

Body:
If your ajax code is in a JS file, could use a hidden input to make the URL available, but not visible on the page, then query the value of the input from JS.

// index.php
<?php
// Get URL
$url = 'chat/9999.html';
?>

<input id="url-from-php" type="hidden" value="<?= $url ?>">

// script.js
$.ajax({
  url: document.getElementById('url-from-php').value,

  cache: false,
  success: function (html) {
    $("#chatbox").html(html); //Insert chat log into the #chatbox div
    var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    if (newscrollHeight > oldscrollHeight) {
      $("#chatbox").animate({ scrollTop: newscrollHeight }, "normal"); //Autoscroll to bottom  of div
    }
  },
});


问:
Compiling libsndfile, and it does not find FLAC
I am trying to cross-compile libsndfile for use on an intel edison, with flac capabilities. I have successfully compiled FLAC, OGG, and VORBIS into my cross toolchain but when I run ./configure it gives me the following output:

```<code>checking for pkg-config... /opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for flac >= 1.3.1 ... no
checking for ogg >= 1.1.3 ... yes
checking for vorbis >= 1.2.3 ... yes
checking for vorbisenc >= 1.2.3 ... yes

configure: WARNING: *** One or more of the external libraries (ie libflac, libogg and
configure: WARNING: *** libvorbis) is either missing (possibly only the development
configure: WARNING: *** headers) or is of an unsupported version.
configure: WARNING: ***
configure: WARNING: *** Unfortunately, for ease of maintenance, the external libs
configure: WARNING: *** are an all or nothing affair.
</code>```

My environmental variables are set up as so:

```<code>export SDKTARGETSYSROOT=/opt/poky-edison/1.7.3/sysroots/core2-32-poky-linux
export PATH=/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/bin:/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/bin/i586-poky-linux:$PATH
export PKG_CONFIG_SYSROOT_DIR=$SDKTARGETSYSROOT
export PKG_CONFIG_PATH=$SDKTARGETSYSROOT/usr/lib/pkgconfig
export CONFIG_SITE=/opt/poky-edison/1.7.3/site-config-core2-32-poky-linux
export OECORE_NATIVE_SYSROOT="/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux"
export OECORE_TARGET_SYSROOT="$SDKTARGETSYSROOT"
export OECORE_ACLOCAL_OPTS="-I /opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/share/aclocal"
export PYTHONHOME=/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr
export CC="i586-poky-linux-gcc  -m32 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -mstackrealign -fno-omit-frame-pointer --sysroot=$SDKTARGETSYSROOT"
export CXX="i586-poky-linux-g++  -m32 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -mstackrealign -fno-omit-frame-pointer --sysroot=$SDKTARGETSYSROOT -I${SDKTARGETSYSROOT}/usr/include/c++/4.9.1 -I${SDKTARGETSYSROOT}/usr/include/c++/4.9.1/i586-poky-linux"
export CPP="i586-poky-linux-gcc -E  -m32 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -mstackrealign -fno-omit-frame-pointer --sysroot=$SDKTARGETSYSROOT"
export AS="i586-poky-linux-as  "
export LD="i586-poky-linux-ld   --sysroot=$SDKTARGETSYSROOT"
export GDB=i586-poky-linux-gdb
export STRIP=i586-poky-linux-strip
export RANLIB=i586-poky-linux-ranlib
export OBJCOPY=i586-poky-linux-objcopy
export OBJDUMP=i586-poky-linux-objdump
export AR=i586-poky-linux-ar
export NM=i586-poky-linux-nm
export M4=m4
export TARGET_PREFIX=i586-poky-linux-
export CONFIGURE_FLAGS="--target=i586-poky-linux --host=i586-poky-linux --build=i686-linux --with-libtool-sysroot=$SDKTARGETSYSROOT"
export CFLAGS=" -O2 -pipe -g -feliminate-unused-debug-types"
export CXXFLAGS=" -O2 -pipe -g -feliminate-unused-debug-types"
export LDFLAGS=""
export CPPFLAGS=""
export KCFLAGS="--sysroot=$SDKTARGETSYSROOT"
export OECORE_DISTRO_VERSION="1.7.3"
export OECORE_SDK_VERSION="1.7.3"
export ARCH=x86
export CROSS_COMPILE=i586-poky-linux-
</code>```

but the flac library is there (in /opt/poky-edison/1.7.3/sysroots/core2-32-poky-linux/usr/local)! I have tried adding explicit paths to the flac library I compiled in a few places but nothing makes a difference. is there a specific place I should try tweaking the paths?

答:
I also had a similar issue in Ubuntu 20.04, while installing another software, It might be helping someone else. I had to install the following way to resolve the issue.

```<code>  sudo apt install libsndfile1-dev

</code>```

Body:
I am trying to cross-compile libsndfile for use on an intel edison, with flac capabilities. I have successfully compiled FLAC, OGG, and VORBIS into my cross toolchain but when I run ./configure it gives me the following output:

checking for pkg-config... /opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for flac >= 1.3.1 ... no
checking for ogg >= 1.1.3 ... yes
checking for vorbis >= 1.2.3 ... yes
checking for vorbisenc >= 1.2.3 ... yes

configure: WARNING: *** One or more of the external libraries (ie libflac, libogg and
configure: WARNING: *** libvorbis) is either missing (possibly only the development
configure: WARNING: *** headers) or is of an unsupported version.
configure: WARNING: ***
configure: WARNING: *** Unfortunately, for ease of maintenance, the external libs
configure: WARNING: *** are an all or nothing affair.

My environmental variables are set up as so:

export SDKTARGETSYSROOT=/opt/poky-edison/1.7.3/sysroots/core2-32-poky-linux
export PATH=/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/bin:/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/bin/i586-poky-linux:$PATH
export PKG_CONFIG_SYSROOT_DIR=$SDKTARGETSYSROOT
export PKG_CONFIG_PATH=$SDKTARGETSYSROOT/usr/lib/pkgconfig
export CONFIG_SITE=/opt/poky-edison/1.7.3/site-config-core2-32-poky-linux
export OECORE_NATIVE_SYSROOT="/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux"
export OECORE_TARGET_SYSROOT="$SDKTARGETSYSROOT"
export OECORE_ACLOCAL_OPTS="-I /opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr/share/aclocal"
export PYTHONHOME=/opt/poky-edison/1.7.3/sysroots/i686-pokysdk-linux/usr
export CC="i586-poky-linux-gcc  -m32 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -mstackrealign -fno-omit-frame-pointer --sysroot=$SDKTARGETSYSROOT"
export CXX="i586-poky-linux-g++  -m32 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -mstackrealign -fno-omit-frame-pointer --sysroot=$SDKTARGETSYSROOT -I${SDKTARGETSYSROOT}/usr/include/c++/4.9.1 -I${SDKTARGETSYSROOT}/usr/include/c++/4.9.1/i586-poky-linux"
export CPP="i586-poky-linux-gcc -E  -m32 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -mstackrealign -fno-omit-frame-pointer --sysroot=$SDKTARGETSYSROOT"
export AS="i586-poky-linux-as  "
export LD="i586-poky-linux-ld   --sysroot=$SDKTARGETSYSROOT"
export GDB=i586-poky-linux-gdb
export STRIP=i586-poky-linux-strip
export RANLIB=i586-poky-linux-ranlib
export OBJCOPY=i586-poky-linux-objcopy
export OBJDUMP=i586-poky-linux-objdump
export AR=i586-poky-linux-ar
export NM=i586-poky-linux-nm
export M4=m4
export TARGET_PREFIX=i586-poky-linux-
export CONFIGURE_FLAGS="--target=i586-poky-linux --host=i586-poky-linux --build=i686-linux --with-libtool-sysroot=$SDKTARGETSYSROOT"
export CFLAGS=" -O2 -pipe -g -feliminate-unused-debug-types"
export CXXFLAGS=" -O2 -pipe -g -feliminate-unused-debug-types"
export LDFLAGS=""
export CPPFLAGS=""
export KCFLAGS="--sysroot=$SDKTARGETSYSROOT"
export OECORE_DISTRO_VERSION="1.7.3"
export OECORE_SDK_VERSION="1.7.3"
export ARCH=x86
export CROSS_COMPILE=i586-poky-linux-

but the flac library is there (in /opt/poky-edison/1.7.3/sysroots/core2-32-poky-linux/usr/local)! I have tried adding explicit paths to the flac library I compiled in a few places but nothing makes a difference. is there a specific place I should try tweaking the paths?

Body:
I also had a similar issue in Ubuntu 20.04, while installing another software, It might be helping someone else. I had to install the following way to resolve the issue.

  sudo apt install libsndfile1-dev


问:
Returning multiple lists from one SQLAlchemy query organized by a dict attribute FLASK
I am trying to write a python function that receives a list of all VolunteerReports from a DB and then organizes them into separate lists based on their "report_category", and returns one dict with many lists inside.

my current function:

```<code>def get_volunteer_reports_for_client(volunteer_id, client_id):
    reports_obj = {}

    volunteer_reports = db_session.query(VolunteerReport).filter(
        VolunteerReport.volunteer_id == volunteer_id, \
            VolunteerReport.client_id == client_id).all()

    if not volunteer_reports:
        return []

    res = [volunteer_report_schema.dump(volunteer_report) for volunteer_report in volunteer_reports]

    for r in res:
        reports_obj[r['report_category']] = [r]

    return reports_obj
</code>```

res returns a list that looks like so:

```<code>[
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:52.538363",
        "id": 1,
        "report": "This is the first report",
        "report_category": "Client Assigned",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:52.623236",
        "id": 2,
        "report": "This is the SECOND report",
        "report_category": "Client Assigned",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:59.493851",
        "id": 3,
        "report": "This is the THIRD report",
        "report_category": "Fulfilled The Need",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:43:06.364411",
        "id": 4,
        "report": "This is the FOURTH report",
        "report_category": "Fulfilled The Need",
        "volunteer_id": 23
    }
]
</code>```

reports_obj currents returns this:

```<code>{
    "Client Assigned": [
        {
            "client_id": 24,
            "created_at": "2022-02-10 16:41:52.623236",
            "id": 2,
            "report": "This is the SECOND report",
            "report_category": "Client Assigned",
            "volunteer_id": 23
        }
    ],
    "Fulfilled The Need": [
        {
            "client_id": 24,
            "created_at": "2022-02-10 16:43:06.364411",
            "id": 4,
            "report": "This is the FOURTH report",
            "report_category": "Fulfilled The Need",
            "volunteer_id": 23
        }
    ]
}
</code>```

At this point, it is omitting some of the entries and only returning the last indexed entry with that "report_category". Any advice?

答:
In every iteration of the loop you are overwriting the current list of dicts in that category with a new list of [r]. You need to append the current dict to the list if the key already exists and otherwise create a new list.

```<code>for r in res:
    category = r['report_category']
    if category in reports_obj:
        reports_obj[category].append(r)
    else:
        reports_obj[category] = [r]
</code>```

Body:
I am trying to write a python function that receives a list of all VolunteerReports from a DB and then organizes them into separate lists based on their "report_category", and returns one dict with many lists inside.

my current function:

def get_volunteer_reports_for_client(volunteer_id, client_id):
    reports_obj = {}

    volunteer_reports = db_session.query(VolunteerReport).filter(
        VolunteerReport.volunteer_id == volunteer_id, \
            VolunteerReport.client_id == client_id).all()

    if not volunteer_reports:
        return []

    res = [volunteer_report_schema.dump(volunteer_report) for volunteer_report in volunteer_reports]

    for r in res:
        reports_obj[r['report_category']] = [r]

    return reports_obj

res returns a list that looks like so:

[
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:52.538363",
        "id": 1,
        "report": "This is the first report",
        "report_category": "Client Assigned",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:52.623236",
        "id": 2,
        "report": "This is the SECOND report",
        "report_category": "Client Assigned",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:59.493851",
        "id": 3,
        "report": "This is the THIRD report",
        "report_category": "Fulfilled The Need",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:43:06.364411",
        "id": 4,
        "report": "This is the FOURTH report",
        "report_category": "Fulfilled The Need",
        "volunteer_id": 23
    }
]

reports_obj currents returns this:

{
    "Client Assigned": [
        {
            "client_id": 24,
            "created_at": "2022-02-10 16:41:52.623236",
            "id": 2,
            "report": "This is the SECOND report",
            "report_category": "Client Assigned",
            "volunteer_id": 23
        }
    ],
    "Fulfilled The Need": [
        {
            "client_id": 24,
            "created_at": "2022-02-10 16:43:06.364411",
            "id": 4,
            "report": "This is the FOURTH report",
            "report_category": "Fulfilled The Need",
            "volunteer_id": 23
        }
    ]
}

At this point, it is omitting some of the entries and only returning the last indexed entry with that "report_category". Any advice?

Body:
In every iteration of the loop you are overwriting the current list of dicts in that category with a new list of [r]. You need to append the current dict to the list if the key already exists and otherwise create a new list.

for r in res:
    category = r['report_category']
    if category in reports_obj:
        reports_obj[category].append(r)
    else:
        reports_obj[category] = [r]


问:
How can avoid nested subscribes with rxjs?
I have rxjs nested observables, which work fine.

```<code>this.service.save(body).subscribe(
   () => {
       this.dialog.confirmDialog({
           title: '',
           message: 'Save okay',
           caption: 'OK'
       })
       .subscribe((yes) => {
            this.service.getGoal().subscribe(
             result => {
                 this.loading(result);
                }
              );
          });
       }
     });
</code>```

The code does three things. First save object, secondly popup a confirmation window. Last call service to refresh the page.
I use nested subscribe here. I know it is not good in theory and I should replace them with rxjs some map function. But I just don't know how?

答:
This should be roughly equivalent without nesting subscriptions:

this.service.save(body).pipe(
  mergeMap(_ => this.dialog.confirmDialog({
    title: '',
    message: 'Save okay',
    caption: 'OK'
  })),
  mergeMap(yes => this.service.getGoal())
).subscribe(result =>
  this.loading(result)
);
```

Body:
I have rxjs nested observables, which work fine.

this.service.save(body).subscribe(
   () => {
       this.dialog.confirmDialog({
           title: '',
           message: 'Save okay',
           caption: 'OK'
       })
       .subscribe((yes) => {
            this.service.getGoal().subscribe(
             result => {
                 this.loading(result);
                }
              );
          });
       }
     });

The code does three things. First save object, secondly popup a confirmation window. Last call service to refresh the page.
I use nested subscribe here. I know it is not good in theory and I should replace them with rxjs some map function. But I just don't know how?


问:
For loop for dataframes in R
I am trying to do a function of decumulation with a for loop in R because the financial information provided by the company is accumulated for different concepts (this means that the info of January is only of January, the info of February is the sum of January and February, the one of March is the sum of January, February and March, etc.).

For example, let's say that I have the next dataframe:

```<code>Concepts <- c("Concept1", "Concept2", "Concept3")
January <- c(5,10,16)
February <- c(9,14,20)
March <- c(16,20,23)

df <- data.frame(Concepts, January, February, March)
</code>```

This will give me the next dataframe:

```<code>Concepts  January  February  March
Concept1    5         9        16
Concept2    10        14       20
Concept3    16        20       23
</code>```

What I need to achieve is the next dataframe (Notice that February is the difference between February and January, and March is the difference between February and March):

```<code>Concepts  January  February  March
Concept1    5         4        7
Concept2    10        4        6
Concept3    16        4        3
</code>```

To achieve the second dataframe, I first created an empty dataframe with the same amount of rows of df, then with a for loop cbind the first two rows of the dataframe (because they do not need any manipulation) and with the index add the next ones after calculated the difference.
The above in code is as follows:

```<code>df <- data.frame(Concepts, January, February, March)
df2 <- data.frame(matrix(nrow=nrow(df),ncol=ncol(df))) #Empty Dataframe with the same number  of rows

for(i in 1:ncol(df)) {
  if(i == 1){
    df2 <- cbind(df2, df[ , i])
  } else if (i == 2){
    df2 <- cbind(df2, df[, i])
  } else {
    diference <- df[,i] - df[,i-1]
    df2 <- cbind(df2,diference)
  }
</code>```

I get the following error:

error in [.data.table(df, , i) :    j (the 2nd argument inside
[...]) is a single symbol but column name 'i' is not found. Perhaps
you intended DT[, ..i]. This difference to data.frame is deliberate
and explained in FAQ 1.1.

I would love to receive a correction to my code or some alternative that allows me to calculate the above for a dataframe of many years.

答:
The solution to my problem was more simple that I expected:

```<code>for(i in 1:ncol(df)) {
  if(i == 1){
   df2 <- cbind(df2, df[ ,..i])
} else if (i == 2){
   df2 <- cbind(df2, df[,..i])
} else {
   diference <- df[,i] - df[,..i-1]
   df2 <- cbind(df2,diference)
}
</code>```

Thanks for all the alternative solutions!

Title: For loop for dataframes in R

Body:
I am trying to do a function of decumulation with a for loop in R because the financial information provided by the company is accumulated for different concepts (this means that the info of January is only of January, the info of February is the sum of January and February, the one of March is the sum of January, February and March, etc.).

For example, let's say that I have the next dataframe:

Concepts <- c("Concept1", "Concept2", "Concept3")
January <- c(5,10,16)
February <- c(9,14,20)
March <- c(16,20,23)

df <- data.frame(Concepts, January, February, March)

This will give me the next dataframe:

Concepts  January  February  March
Concept1    5         9        16
Concept2    10        14       20
Concept3    16        20       23

What I need to achieve is the next dataframe (Notice that February is the difference between February and January, and March is the difference between February and March):

Concepts  January  February  March
Concept1    5         4        7
Concept2    10        4        6
Concept3    16        4        3

To achieve the second dataframe, I first created an empty dataframe with the same amount of rows of df, then with a for loop cbind the first two rows of the dataframe (because they do not need any manipulation) and with the index add the next ones after calculated the difference.
The above in code is as follows:

df <- data.frame(Concepts, January, February, March)
df2 <- data.frame(matrix(nrow=nrow(df),ncol=ncol(df))) #Empty Dataframe with the same number  of rows

for(i in 1:ncol(df)) {
  if(i == 1){
    df2 <- cbind(df2, df[ , i])
  } else if (i == 2){
    df2 <- cbind(df2, df[, i])
  } else {
    diference <- df[,i] - df[,i-1]
    df2 <- cbind(df2,diference)
  }

I get the following error:

error in [.data.table(df, , i) :    j (the 2nd argument inside
[...]) is a single symbol but column name 'i' is not found. Perhaps
you intended DT[, ..i]. This difference to data.frame is deliberate
and explained in FAQ 1.1.

I would love to receive a correction to my code or some alternative that allows me to calculate the above for a dataframe of many years.

Body:
The solution to my problem was more simple that I expected:

for(i in 1:ncol(df)) {
  if(i == 1){
   df2 <- cbind(df2, df[ ,..i])
} else if (i == 2){
   df2 <- cbind(df2, df[,..i])
} else {
   diference <- df[,i] - df[,..i-1]
   df2 <- cbind(df2,diference)
}

Thanks for all the alternative solutions!


问:
The return types for the following stored procedures could not be detected
While drag-drop a stored procedure in dbml file I get this error:

Unknown Return Type

  The return types for the following stored procedures could not be detected. Set the return type for each stored procedure in the Properties window.

How can I resolve this error?

答: The issue for me was that I had OPTION (RECOMPILE) set to get round a parameter sniffing issue. I temporary removed this while adding the SP and all worked fine.</p>


问:
Smarty - foreach stops while reaching a limit
i have a smarty foreach loop over a list of elements. this loop must stop when it complete 10 iteration, ie foreach must end at the 10th element of list.</p>
```<code>{foreach $b_list as $list}
     <label>{$list['firstname']}</label>
{/foreach}
</code>```

答:
```<code>{foreach $b_list as $list}
    <label>{$list['firstname']}</label>
    {if $list@iteration == 10}
        {break}
    {/if}
{/foreach}
</code>```

Body:
i have a smarty foreach loop over a list of elements. this loop must stop when it complete 10 iteration, ie foreach must end at the 10th element of list.

{foreach $b_list as $list}
     {$list['firstname']}
{/foreach}


答:
You should use RxJs operators to make your observable stream cleaner. Depending on your use case, some common operators include mergeMap, switchMap, map, e.t.c.

Nesting subscribes can cause problems such as memory leaks.

Title: How can avoid nested subscribes with rxjs?


问:
Upgrading to Symfony 6 from 5.3
I updated my composer.json file to reflect the 6.0.* changes, and ran my composer update "symfony/*" code, and it returned this:

```<code>    Problem 1
    - doctrine/doctrine-bundle is locked to version 2.4.3 and an update of this package was not requested.
    - doctrine/doctrine-bundle 2.4.3 requires symfony/config ^4.4.3|^5.0|^6.0 -> found symfony/config[v4.4.3, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 2
    - sensio/framework-extra-bundle is locked to version v5.6.1 and an update of this package was not requested.
    - sensio/framework-extra-bundle v5.6.1 requires symfony/config ^4.4|^5.0 -> found symfony/config[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 3
    - Root composer.json requires symfony/security-http 6.0.* -> satisfiable by symfony/security-http[v6.0.0-BETA1, ..., 6.0.x-dev].
    - symfony/security-http[v6.0.0-BETA1, ..., 6.0.x-dev] require symfony/http-kernel ^5.4|^6.0 -> found symfony/http-kernel[v5.4.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 4
    - symfonycasts/reset-password-bundle is locked to version v1.10.0 and an update of this package was not requested.
    - symfonycasts/reset-password-bundle v1.10.0 requires symfony/config ^4.4 | ^5.0 | ^6.0 -> found symfony/config[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 5
    - symfonycasts/verify-email-bundle is locked to version v1.6.0 and an update of this package was not requested.
    - symfonycasts/verify-email-bundle v1.6.0 requires symfony/config ^4.4 | ^5.0 | ^6.0 -> found symfony/config[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 6
    - doctrine/doctrine-fixtures-bundle is locked to version 3.4.1 and an update of this package was not requested.
    - doctrine/doctrine-fixtures-bundle 3.4.1 requires symfony/config ^3.4|^4.3|^5.0|^6.0 -> found symfony/config[v3.4.0-BETA1, ..., 3.4.x-dev, v4.3.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 7
    - doctrine/doctrine-bundle 2.4.3 requires symfony/config ^4.4.3|^5.0|^6.0 -> found symfony/config[v4.4.3, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
    - doctrine/doctrine-migrations-bundle 3.2.1 requires doctrine/doctrine-bundle ~1.0|~2.0 -> satisfiable by doctrine/doctrine-bundle[2.4.3].
    - doctrine/doctrine-migrations-bundle is locked to version 3.2.1 and an update of this package was not requested.
</code>```

Some of these notifications confuse me because I'm not sure what to do when a package is locked a version.

Here is my composer.json file:

```<code>{
    "type": "project",
    "license": "proprietary",
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "php": ">=7.2.5",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "1.11.99.1",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.3",
        "doctrine/doctrine-migrations-bundle": "^3.0",
        "doctrine/orm": "^2.8",
        "phpdocumentor/reflection-docblock": "^5.2",
        "sensio/framework-extra-bundle": "^5.1",
        "stripe/stripe-php": "^7.76",
        "symfony/asset": "6.0.*",
        "symfony/console": "6.0.*",
        "symfony/dotenv": "6.0.*",
        "symfony/expression-language": "6.0.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "6.0.*",
        "symfony/framework-bundle": "5.3.*",
        "symfony/http-client": "6.0.*",
        "symfony/intl": "6.0.*",
        "symfony/mailer": "6.0.*",
        "symfony/mime": "6.0.*",
        "symfony/monolog-bundle": "^3.7",
        "symfony/notifier": "6.0.*",
        "symfony/postmark-mailer": "6.0.*",
        "symfony/process": "6.0.*",
        "symfony/property-access": "6.0.*",
        "symfony/property-info": "6.0.*",
        "symfony/proxy-manager-bridge": "6.0.*",
        "symfony/rate-limiter": "6.0.*",
        "symfony/security-bundle": "6.0.*",
        "symfony/security-core": "6.0.*",
        "symfony/security-csrf": "6.0.*",
        "symfony/security-guard": "5.3.*",
        "symfony/security-http": "6.0.*",
        "symfony/serializer": "6.0.*",
        "symfony/string": "6.0.*",
        "symfony/translation": "6.0.*",
        "symfony/twig-bundle": "^5.3",
        "symfony/validator": "6.0.*",
        "symfony/web-link": "6.0.*",
        "symfony/webpack-encore-bundle": "^1.11",
        "symfony/yaml": "6.0.*",
        "symfonycasts/reset-password-bundle": "^1.7",
        "symfonycasts/verify-email-bundle": "^1.3",
        "taxjar/taxjar-php": "^1.10",
        "twig/cssinliner-extra": "^3.3",
        "twig/extra-bundle": "^3.3",
        "twig/inky-extra": "^3.3",
        "twig/intl-extra": "^3.3",
        "twig/twig": "^2.12|^3.0"
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4",
        "symfony/browser-kit": "^5.3",
        "symfony/css-selector": "^5.3",
        "symfony/debug-bundle": "^5.3",
        "symfony/maker-bundle": "^1.0",
        "symfony/phpunit-bridge": "^5.3",
        "symfony/stopwatch": "^5.3",
        "symfony/var-dumper": "^5.3",
        "symfony/web-profiler-bundle": "^5.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true,
        "allow-plugins": {
            "symfony/flex": true
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "6.0.*"
        }
    }
}
</code>```

How do I resolve these problems and also what can I do moving forward so I can be more aware of how to fix these on my own?

答:
That composer.json file is a bit of a mess. Some Symfony packages on 5.3, some even on 5.1, and many on 6.

Also you are controlling Symfony versioning from extra.symfony.require, and at the same time from the discrete version constraints. You include some packages that no longer exist on 6.0 (symfony/security-guard), and are missing some that should be installed on a 6.0 version.

It's simply not on an installable state.

I've managed to make it installable changing it like this:

{
    "type": "project",
    "license": "proprietary",
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "php": ">=7.2.5",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "1.11.99.1",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.3",
        "doctrine/doctrine-migrations-bundle": "^3.0",
        "doctrine/orm": "^2.8",
        "phpdocumentor/reflection-docblock": "^5.2",
        "sensio/framework-extra-bundle": "^6.0.0",
        "stripe/stripe-php": "^7.76",
        "symfony/asset": "*",
        "symfony/console": "*",
        "symfony/dotenv": "*",
        "symfony/expression-language": "*",
        "symfony/flex": "v2.1.4",
        "symfony/form": "*",
        "symfony/framework-bundle": "*",
        "symfony/http-client": "*",
        "symfony/intl": "*",
        "symfony/mailer": "*",
        "symfony/mime": "*",
        "symfony/monolog-bundle": "^3.7",
        "symfony/notifier": "*",
        "symfony/postmark-mailer": "*",
        "symfony/process": "*",
        "symfony/property-access": "*",
        "symfony/property-info": "*",
        "symfony/proxy-manager-bridge": "*",
        "symfony/rate-limiter": "*",
        "symfony/runtime": "*",
        "symfony/security-bundle": "*",
        "symfony/security-core": "*",
        "symfony/security-csrf": "*",
        "symfony/security-http": "*",
        "symfony/serializer": "*",
        "symfony/string": "*",
        "symfony/translation": "*",
        "symfony/twig-bundle": "*",
        "symfony/validator": "*",
        "symfony/web-link": "*",
        "symfony/webpack-encore-bundle": "^1.11",
        "symfony/yaml": "*",
        "symfonycasts/reset-password-bundle": "^1.7",
        "symfonycasts/verify-email-bundle": "^1.3",
        "taxjar/taxjar-php": "^1.10",
        "twig/cssinliner-extra": "^3.3",
        "twig/extra-bundle": "^3.3",
        "twig/inky-extra": "^3.3",
        "twig/intl-extra": "^3.3",
        "twig/twig": "^2.12|^3.0"
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4",
        "symfony/browser-kit": "*",
        "symfony/css-selector": "*",
        "symfony/debug-bundle": "*",
        "symfony/maker-bundle": "^1.0",
        "symfony/phpunit-bridge": "*",
        "symfony/stopwatch": "*",
        "symfony/var-dumper": "*",
        "symfony/web-profiler-bundle": "*"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true,
        "allow-plugins": {
            "symfony/flex": true,
            "composer/package-versions-deprecated": false,
            "symfony/runtime": true
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "6.0.*",
            "docker": true
        }
    }
}
```

Since this will not match your locked versions, I would simply delete your vendor directory and your composer.lock and run composer install. You'll have to deal with all the different changes from the new recipes, but hopefully this is version-controlled project so it's a matter of going through the changes and see where what issues arise.

It's going to be fun.

Title: Upgrading to Symfony 6 from 5.3

Body:
I updated my composer.json file to reflect the 6.0.* changes, and ran my composer update "symfony/*" code, and it returned this:

    Problem 1
    - doctrine/doctrine-bundle is locked to version 2.4.3 and an update of this package was not requested.
    - doctrine/doctrine-bundle 2.4.3 requires symfony/config ^4.4.3|^5.0|^6.0 -> found symfony/config[v4.4.3, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 2
    - sensio/framework-extra-bundle is locked to version v5.6.1 and an update of this package was not requested.
    - sensio/framework-extra-bundle v5.6.1 requires symfony/config ^4.4|^5.0 -> found symfony/config[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 3
    - Root composer.json requires symfony/security-http 6.0.* -> satisfiable by symfony/security-http[v6.0.0-BETA1, ..., 6.0.x-dev].
    - symfony/security-http[v6.0.0-BETA1, ..., 6.0.x-dev] require symfony/http-kernel ^5.4|^6.0 -> found symfony/http-kernel[v5.4.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 4
    - symfonycasts/reset-password-bundle is locked to version v1.10.0 and an update of this package was not requested.
    - symfonycasts/reset-password-bundle v1.10.0 requires symfony/config ^4.4 | ^5.0 | ^6.0 -> found symfony/config[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 5
    - symfonycasts/verify-email-bundle is locked to version v1.6.0 and an update of this package was not requested.
    - symfonycasts/verify-email-bundle v1.6.0 requires symfony/config ^4.4 | ^5.0 | ^6.0 -> found symfony/config[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 6
    - doctrine/doctrine-fixtures-bundle is locked to version 3.4.1 and an update of this package was not requested.
    - doctrine/doctrine-fixtures-bundle 3.4.1 requires symfony/config ^3.4|^4.3|^5.0|^6.0 -> found symfony/config[v3.4.0-BETA1, ..., 3.4.x-dev, v4.3.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
  Problem 7
    - doctrine/doctrine-bundle 2.4.3 requires symfony/config ^4.4.3|^5.0|^6.0 -> found symfony/config[v4.4.3, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev, v6.0.0-BETA1, ..., 6.1.x-dev] but these were not loaded, likely because it conflicts with another require.
    - doctrine/doctrine-migrations-bundle 3.2.1 requires doctrine/doctrine-bundle ~1.0|~2.0 -> satisfiable by doctrine/doctrine-bundle[2.4.3].
    - doctrine/doctrine-migrations-bundle is locked to version 3.2.1 and an update of this package was not requested.

Some of these notifications confuse me because I'm not sure what to do when a package is locked a version.

Here is my composer.json file:

{
    "type": "project",
    "license": "proprietary",
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "php": ">=7.2.5",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "1.11.99.1",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.3",
        "doctrine/doctrine-migrations-bundle": "^3.0",
        "doctrine/orm": "^2.8",
        "phpdocumentor/reflection-docblock": "^5.2",
        "sensio/framework-extra-bundle": "^5.1",
        "stripe/stripe-php": "^7.76",
        "symfony/asset": "6.0.*",
        "symfony/console": "6.0.*",
        "symfony/dotenv": "6.0.*",
        "symfony/expression-language": "6.0.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "6.0.*",
        "symfony/framework-bundle": "5.3.*",
        "symfony/http-client": "6.0.*",
        "symfony/intl": "6.0.*",
        "symfony/mailer": "6.0.*",
        "symfony/mime": "6.0.*",
        "symfony/monolog-bundle": "^3.7",
        "symfony/notifier": "6.0.*",
        "symfony/postmark-mailer": "6.0.*",
        "symfony/process": "6.0.*",
        "symfony/property-access": "6.0.*",
        "symfony/property-info": "6.0.*",
        "symfony/proxy-manager-bridge": "6.0.*",
        "symfony/rate-limiter": "6.0.*",
        "symfony/security-bundle": "6.0.*",
        "symfony/security-core": "6.0.*",
        "symfony/security-csrf": "6.0.*",
        "symfony/security-guard": "5.3.*",
        "symfony/security-http": "6.0.*",
        "symfony/serializer": "6.0.*",
        "symfony/string": "6.0.*",
        "symfony/translation": "6.0.*",
        "symfony/twig-bundle": "^5.3",
        "symfony/validator": "6.0.*",
        "symfony/web-link": "6.0.*",
        "symfony/webpack-encore-bundle": "^1.11",
        "symfony/yaml": "6.0.*",
        "symfonycasts/reset-password-bundle": "^1.7",
        "symfonycasts/verify-email-bundle": "^1.3",
        "taxjar/taxjar-php": "^1.10",
        "twig/cssinliner-extra": "^3.3",
        "twig/extra-bundle": "^3.3",
        "twig/inky-extra": "^3.3",
        "twig/intl-extra": "^3.3",
        "twig/twig": "^2.12|^3.0"
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4",
        "symfony/browser-kit": "^5.3",
        "symfony/css-selector": "^5.3",
        "symfony/debug-bundle": "^5.3",
        "symfony/maker-bundle": "^1.0",
        "symfony/phpunit-bridge": "^5.3",
        "symfony/stopwatch": "^5.3",
        "symfony/var-dumper": "^5.3",
        "symfony/web-profiler-bundle": "^5.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true,
        "allow-plugins": {
            "symfony/flex": true
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "6.0.*"
        }
    }
}

How do I resolve these problems and also what can I do moving forward so I can be more aware of how to fix these on my own?

Body:
That composer.json file is a bit of a mess. Some Symfony packages on 5.3, some even on 5.1, and many on 6.

Also you are controlling Symfony versioning from extra.symfony.require, and at the same time from the discrete version constraints. You include some packages that no longer exist on 6.0 (symfony/security-guard), and are missing some that should be installed on a 6.0 version.

It's simply not on an installable state.

I've managed to make it installable changing it like this:

{
    "type": "project",
    "license": "proprietary",
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "php": ">=7.2.5",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "1.11.99.1",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.3",
        "doctrine/doctrine-migrations-bundle": "^3.0",
        "doctrine/orm": "^2.8",
        "phpdocumentor/reflection-docblock": "^5.2",
        "sensio/framework-extra-bundle": "^6.0.0",
        "stripe/stripe-php": "^7.76",
        "symfony/asset": "*",
        "symfony/console": "*",
        "symfony/dotenv": "*",
        "symfony/expression-language": "*",
        "symfony/flex": "v2.1.4",
        "symfony/form": "*",
        "symfony/framework-bundle": "*",
        "symfony/http-client": "*",
        "symfony/intl": "*",
        "symfony/mailer": "*",
        "symfony/mime": "*",
        "symfony/monolog-bundle": "^3.7",
        "symfony/notifier": "*",
        "symfony/postmark-mailer": "*",
        "symfony/process": "*",
        "symfony/property-access": "*",
        "symfony/property-info": "*",
        "symfony/proxy-manager-bridge": "*",
        "symfony/rate-limiter": "*",
        "symfony/runtime": "*",
        "symfony/security-bundle": "*",
        "symfony/security-core": "*",
        "symfony/security-csrf": "*",
        "symfony/security-http": "*",
        "symfony/serializer": "*",
        "symfony/string": "*",
        "symfony/translation": "*",
        "symfony/twig-bundle": "*",
        "symfony/validator": "*",
        "symfony/web-link": "*",
        "symfony/webpack-encore-bundle": "^1.11",
        "symfony/yaml": "*",
        "symfonycasts/reset-password-bundle": "^1.7",
        "symfonycasts/verify-email-bundle": "^1.3",
        "taxjar/taxjar-php": "^1.10",
        "twig/cssinliner-extra": "^3.3",
        "twig/extra-bundle": "^3.3",
        "twig/inky-extra": "^3.3",
        "twig/intl-extra": "^3.3",
        "twig/twig": "^2.12|^3.0"
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4",
        "symfony/browser-kit": "*",
        "symfony/css-selector": "*",
        "symfony/debug-bundle": "*",
        "symfony/maker-bundle": "^1.0",
        "symfony/phpunit-bridge": "*",
        "symfony/stopwatch": "*",
        "symfony/var-dumper": "*",
        "symfony/web-profiler-bundle": "*"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true,
        "allow-plugins": {
            "symfony/flex": true,
            "composer/package-versions-deprecated": false,
            "symfony/runtime": true
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php72": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "6.0.*",
            "docker": true
        }
    }
}

Since this will not match your locked versions, I would simply delete your vendor directory and your composer.lock and run composer install. You'll have to deal with all the different changes from the new recipes, but hopefully this is version-controlled project so it's a matter of going through the changes and see where what issues arise.

It's going to be fun.


问:
Styling DataGridCell correctly
This is a question following my previous problem, you can find it right there

So. Now I defined a DataGrid with a specific ElementStyle for each column (which just defines the TextBlocks inside in bold & white -- will come over this problem later)

So now I have two questions

First question (solved)

When I happen to set a background to my cell, it overrides the default style, and the background stays the same when the cell is highlighted.

One example of a style:

```<code><!-- Green template for market-related -->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
    <Grid Background="Green">
        <ContentPresenter
                        HorizontalAlignment="Center"
                                  VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>
</code>```

I'd naturally say that this is "normal" because I set the Grid's background to Green. I therefore tried it this way:

```<code><!-- Light green template for sophis-related -->
<ControlTemplate x:Key="LightGreen" TargetType="{x:Type tk:DataGridCell}">
    <Grid Background="LightGreen">
        <Grid.Resources>
            <Style TargetType="{x:Type Grid}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tk:DataGridCell}},
                                            Converter={StaticResource DebugConverter}}" Value="True">
                        <Setter Property="Grid.Background" Value="#FF3774FF" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>
</code>```

This won't work either. As you can see I put a DebugConverter so I can check that the trigger is actually called, which is the case, but... Background does not change (and Snoop confirms this...)

Third try:

```<code><!-- Light green template for sophis-related -->
<ControlTemplate x:Key="LightGreen" TargetType="{x:Type tk:DataGridCell}">
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type tk:DataGridCell}">
            <Setter Property="Background" Value="LightGreen" />
        </Style>
    </ControlTemplate.Resources>
    <Grid>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>
</code>```

And... No background will be displayed (stays transparent)

So I think I am working in the wrong way here and I was wondering what should I do to JUST define the "not selected" template.
I would say that I may need to define a style BasedOn the "classic" style but, how would I do that? I tried to add TemplateBindings with no success

** EDIT: Solution**

As H B suggested in his answer, problem was coming from DependencyProperty Precedence, here's the solution:

```<code><!-- Light green template for sophis-related -->
<ControlTemplate x:Key="LightGreen" TargetType="{x:Type tk:DataGridCell}">
    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type Grid}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tk:DataGridCell}},
                                            Converter={StaticResource DebugConverter}}" Value="True">
                        <Setter Property="Grid.Background" Value="#FF316AC5" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tk:DataGridCell}},
                                            Converter={StaticResource DebugConverter}}" Value="False">
                        <Setter Property="Grid.Background" Value="LightGreen" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>
</code>```

Second question

Now, let's speak Triggers.

Basically, what I want to do is to define specific Triggers to my ElementStyle so the font color is white if the cell's background is Red or Green (the only aim of this is to have a better readability as Red and Green are kinda dark, black font on dark background results in a nice fail :p )

Edit Seems like I'm not clear enough: the following style is the style applied to each item of the datagrid, through the property DataGridTextColumn.ElementStyle. Here is the code handling that:

```<code>    void VolatilityDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        DataGridTextColumn column = e.Column as DataGridTextColumn;
        column.ElementStyle = s_boldCellStyle;
        // Other stuff here...
    }
</code>```

Here is what I do:

```<code><!-- Cell style for colored matrix-->
<Style x:Key="BoldCellStyle" TargetType="{x:Type TextBlock}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Background, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tk:DataGridCell}}}"
                     Value="Red">
            <Setter Property="Foreground" Value="White" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Background, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tk:DataGridCell}},
                                Converter={StaticResource DebugConverter}}"
                     Value="Green">
            <Setter Property="Foreground" Value="White" />
        </DataTrigger>
    </Style.Triggers>
    <Setter Property="FontWeight" Value="Bold"/>
</Style>
</code>```

And... It doesn't work. Strangely, what goes through converter is ONLY transparent background colors. I am definitely missing something here!
BTW, I also tried with classic triggers, no success either, I use DataTriggers here so I can debug the binding values!

Now I've been stuck for more than three days on this and I'm starting to freak out... Hopefully the Stackoverflow community will save me :)

Thanks!

Edit

Okay, update.
I understood why my Trigger does not work. The Background actually set is on the Grid and NOT on the DataGridCell. It is therefore normal that I don't get any color set there.

However, I ran some tests and found out that when the binding is set, the TextBlock does not have any parent yet (Parent = null). Binding to a RelativeSource of type Grid will bind me to... The whole DataGrid items presenter.
I'm not sure what to do now, since it seems like that from the actual TextBlock style I can't reach the parent Grid and therefore cannot resolve what color should I display according to the background.
Also, I can't change the Font color in my ControlTemplate because the DataGrid wants a Style for each column, which overrides the template's style by default (see my previous question and its answer)
So... Stuck again I am!

答:
Dependency Property Value Precedence

This:

```<code><Grid Background="LightGreen">
    <Grid.Resources>
        <Style TargetType="{x:Type Grid}">
            <!-- Trigger Stuff -->
        </Style>
    </Grid.Resources>
    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</code>```

Needs to be:

```<code><Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Grid}">
            <Setter Property="Background" Value="LightGreen"/>
            <!-- Trigger Stuff -->
        </Style>
    </Grid.Resources>
    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</code>```

Not sure about your second question as of now, possibly a related problem, i would suggest setting TextElement.Foreground instead of Foreground for starters. Getting Transparent as value is not very helpful, what control template do you use for the DataGridCell? If it is custom, is the Background hooked up properly via a TemplateBinding?

This works as long as the Background property is used, so if you have a ControlTemplate which sets things internally you need to externalize that. A normal DataGrid example:

```<code><DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Background" Value="LightGreen"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Content}" Value="Apple">
                <Setter Property="Background" Value="Red"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Content}" Value="Tomato">
                <Setter Property="Background" Value="Green"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>
</code>```

```<code><Style TargetType="TextBlock">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}}" Value="Red">
            <Setter Property="Foreground" Value="White"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}}" Value="Green">
            <Setter Property="Foreground" Value="White"/>
        </DataTrigger>
    </Style.Triggers>
    <Setter Property="FontWeight" Value="Bold"/>
</Style>
</code>```

So if the CellStyle sets the ControlTemplate the properties need to be hooked up via TemplateBinding. e.g.

```<code><DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Background" Value="LightGreen"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Content}" Value="Apple">
                <Setter Property="Background" Value="Red"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Content}" Value="Tomato">
                <Setter Property="Background" Value="Green"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>
</code>```

Do not do the triggering inside the template or it will get messy.

Title: Styling DataGridCell correctly

Body:
This is a question following my previous problem, you can find it right there

So. Now I defined a DataGrid with a specific ElementStyle for each column (which just defines the TextBlocks inside in bold & white -- will come over this problem later)

So now I have two questions

First question (solved)

When I happen to set a background to my cell, it overrides the default style, and the background stays the same when the cell is highlighted.

One example of a style:

<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
    <Grid Background="Green">
        <ContentPresenter
                        HorizontalAlignment="Center"
                                  VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>

I'd naturally say that this is "normal" because I set the Grid's background to Green. I therefore tried it this way:

<ControlTemplate x:Key="LightGreen" TargetType="{x:Type tk:DataGridCell}">
    <Grid Background="LightGreen">
        <Grid.Resources>

            </Style>
        </Grid.Resources>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>

This won't work either. As you can see I put a DebugConverter so I can check that the trigger is actually called, which is the case, but... Background does not change (and Snoop confirms this...)

Third try:

<ControlTemplate x:Key="LightGreen" TargetType="{x:Type tk:DataGridCell}">
    <ControlTemplate.Resources>

    </ControlTemplate.Resources>
    <Grid>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>

And... No background will be displayed (stays transparent)

So I think I am working in the wrong way here and I was wondering what should I do to JUST define the "not selected" template.
I would say that I may need to define a style BasedOn the "classic" style but, how would I do that? I tried to add TemplateBindings with no success

** EDIT: Solution**

As H B suggested in his answer, problem was coming from DependencyProperty Precedence, here's the solution:

<ControlTemplate x:Key="LightGreen" TargetType="{x:Type tk:DataGridCell}">
    <Grid>
        <Grid.Resources>

            </Style>
        </Grid.Resources>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>

Second question

Now, let's speak Triggers.

Basically, what I want to do is to define specific Triggers to my ElementStyle so the font color is white if the cell's background is Red or Green (the only aim of this is to have a better readability as Red and Green are kinda dark, black font on dark background results in a nice fail :p )

Edit Seems like I'm not clear enough: the following style is the style applied to each item of the datagrid, through the property DataGridTextColumn.ElementStyle. Here is the code handling that:

    void VolatilityDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        DataGridTextColumn column = e.Column as DataGridTextColumn;
        column.ElementStyle = s_boldCellStyle;
        // Other stuff here...
    }

Here is what I do:

    <Setter Property="FontWeight" Value="Bold"/>
</Style>

And... It doesn't work. Strangely, what goes through converter is ONLY transparent background colors. I am definitely missing something here!
BTW, I also tried with classic triggers, no success either, I use DataTriggers here so I can debug the binding values!

Now I've been stuck for more than three days on this and I'm starting to freak out... Hopefully the Stackoverflow community will save me :)

Thanks!

Edit

Okay, update.
I understood why my Trigger does not work. The Background actually set is on the Grid and NOT on the DataGridCell. It is therefore normal that I don't get any color set there.

However, I ran some tests and found out that when the binding is set, the TextBlock does not have any parent yet (Parent = null). Binding to a RelativeSource of type Grid will bind me to... The whole DataGrid items presenter.
I'm not sure what to do now, since it seems like that from the actual TextBlock style I can't reach the parent Grid and therefore cannot resolve what color should I display according to the background.
Also, I can't change the Font color in my ControlTemplate because the DataGrid wants a Style for each column, which overrides the template's style by default (see my previous question and its answer)
So... Stuck again I am!

Body:
Dependency Property Value Precedence

This:

<Grid Background="LightGreen">
    <Grid.Resources>
        <Style TargetType="{x:Type Grid}">
            <!-- Trigger Stuff -->
        </Style>
    </Grid.Resources>
    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

Needs to be:

<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Grid}">
            <Setter Property="Background" Value="LightGreen"/>
            <!-- Trigger Stuff -->
        </Style>
    </Grid.Resources>
    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

Not sure about your second question as of now, possibly a related problem, i would suggest setting TextElement.Foreground instead of Foreground for starters. Getting Transparent as value is not very helpful, what control template do you use for the DataGridCell? If it is custom, is the Background hooked up properly via a TemplateBinding?

This works as long as the Background property is used, so if you have a ControlTemplate which sets things internally you need to externalize that. A normal DataGrid example:

<DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Background" Value="LightGreen"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Content}" Value="Apple">
                <Setter Property="Background" Value="Red"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Content}" Value="Tomato">
                <Setter Property="Background" Value="Green"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>

<Style TargetType="TextBlock">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}}" Value="Red">
            <Setter Property="Foreground" Value="White"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}}" Value="Green">
            <Setter Property="Foreground" Value="White"/>
        </DataTrigger>
    </Style.Triggers>
    <Setter Property="FontWeight" Value="Bold"/>
</Style>

So if the CellStyle sets the ControlTemplate the properties need to be hooked up via TemplateBinding. e.g.

<DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Background" Value="LightGreen"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Content}" Value="Apple">
                <Setter Property="Background" Value="Red"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Content}" Value="Tomato">
                <Setter Property="Background" Value="Green"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>

Do not do the triggering inside the template or it will get messy.


问:
How to append a line from .txt file without new line character "/n"
I have to read a txt file with for example this:

```<code>test
test2
test3
test4
</code>```

If I use a this code

```<code>read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.readlines()
print(read_of_string)
</code>```

a output is ["test/n","test2/n","test3/n","test4/n"]

if I use this code

```<code>print(read_of_string[0])
</code>```

output is "test" (enter)

I have to append it into a

```<code>listofstring = []
listofsting.append(read_of_string)
</code>```

it is not working
Output should be a list with strings without enters like

```<code>["test","test2","test3","test4"]
</code>```

答:
Simply use the str.splitlines() method:

```<code>read_of_string = read_of_string.read().splitlines()
</code>```

So in your code, it should be:

```<code>read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.read().splitlines()
print(read_of_string)
</code>```

But do note that it is a better practice to use the with handler to open files:

```<code>with open("mylink.txt", "r") as r:
    read_of_string = r.read().splitlines()
    print(read_of_string)
</code>```

Body:
I have to read a txt file with for example this:

test
test2
test3
test4

If I use a this code

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.readlines()
print(read_of_string)

a output is ["test/n","test2/n","test3/n","test4/n"]

if I use this code

print(read_of_string[0])

output is "test" (enter)

I have to append it into a

listofstring = []
listofsting.append(read_of_string)

it is not working
Output should be a list with strings without enters like

["test","test2","test3","test4"]

Body:
Simply use the str.splitlines() method:

read_of_string = read_of_string.read().splitlines()

So in your code, it should be:

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.read().splitlines()
print(read_of_string)

But do note that it is a better practice to use the with handler to open files:

with open("mylink.txt", "r") as r:
    read_of_string = r.read().splitlines()
    print(read_of_string)


问:
How can I combine rank=same with dir=back, while specifying ports?
I have a graph that uses HTML-like labels to create tables where some cells are connected by an edge.

This works well, but when I specify rank=same for two nodes, dir=back for the connecting edge and at least one port position the edge direction is not respected.

This shows an example:

```<code>digraph so {
    // This all works
    a -> b [label="Regular direction" dir="forward"]
    c -> d [label="Reverse direction", dir="back"]
    e:w -> f:w [label="Reverse direction\n + port choice", dir="back"]
    g -> h [label="Reverse direction\n + rank=same", dir="back"]
    {rank=same; g; h}

    // This fails
    i:s -> j [label="Reverse direction\n + port choice\n + rank=same", dir="back"]
    {rank=same i; j}
}
</code>```

I've highlighted the failing part below:

Is there a combination of graph/node/edge options that would allow me to draw a reverse edge from one node port to another, while the two nodes are at the same rank?

What I've tried

Instead of using dir=back on the edge, I tried setting the arrowhead=none and arrowtail=normal in combination with dir=both. That didn't work either and somehow even affects the  i -> j edge as well.

```<code>digraph so {
    // This fails
    i:s -> j [label="Reverse direction\n + port choice\n + rank=same", dir="back"]
    {rank=same i; j}

    // This fails
    k:s -> l [label="Reverse direction\n + port choice\n + rank=same\n + arrowhead/tail", arrowhead=none, arrowtail=normal, dir="both"]
    {rank=same k; l}
}
</code>```

答:
I found that mentioning the dir attribute before the label attribute gets you what you want:

```<code>digraph so {
    i:s -> j [dir="back", label="Reverse direction\n + port choice\n + rank=same"]
    {rank=same; i;j}
}
</code>```

Body:
I have a graph that uses HTML-like labels to create tables where some cells are connected by an edge.

This works well, but when I specify rank=same for two nodes, dir=back for the connecting edge and at least one port position the edge direction is not respected.

This shows an <a href="http://magjac.com/graphviz-visual-editor/?dot=digraph%20so%20%7B%0D%0A%20%20%20%20%2F%2F%20This%20all%20works%0D%0A%20%20%20%20a%20-%3E%20b%20%5Blabel%3D%22Regular%20direction%22%20dir%3D%22forward%22%5D%0D%0A%20%20%20%20c%20-%3E%20d%20%5Blabel%3D%22Reverse%20direction%22%2C%20dir%3D%22back%22%5D%0D%0A%20%20%20%20e%3Aw%20-%3E%20f%3Aw%20%5Blabel%3D%22Reverse%20direction%5Cn%20%2B%20port%20choice%22%2C%20dir%3D%22back%22%5D%0D%0A%20%20%20%20g%20-%3E%20h%20%5Blabel%3D%22Reverse%20direction%5Cn%20%2B%20rank%3Dsame%22%2C%20dir%3D%22back%22%5D%0D%0A%20%20%20%20%7Brank%3Dsame%3B%20g%3B%20h%7D%0D%0A%20%20%20%20%0D%0A%20%20%20%20%2F%2F%20This%20fails%0D%0A%20%20%20%20i%3As%20-%3E%20j%20%5Blabel%3D%22Reverse%20direction%5Cn%20%2B%20port%20choice%5Cn%20%2B%20rank%3Dsame%22%2C%20dir%3D%22back%22%5D%0D%0A%20%20%20%20%7Brank%3Dsame%20i%3B%20j%7D%0D%0A%7D" rel="nofollow noreferrer">example:

digraph so {
    // This all works
    a -> b [label="Regular direction" dir="forward"]
    c -> d [label="Reverse direction", dir="back"]
    e:w -> f:w [label="Reverse direction\n + port choice", dir="back"]
    g -> h [label="Reverse direction\n + rank=same", dir="back"]
    {rank=same; g; h}

    // This fails
    i:s -> j [label="Reverse direction\n + port choice\n + rank=same", dir="back"]
    {rank=same i; j}
}

I've highlighted the failing part below:

Is there a combination of graph/node/edge options that would allow me to draw a reverse edge from one node port to another, while the two nodes are at the same rank?

What I've tried

Instead of using dir=back on the edge, I tried setting the arrowhead=none and arrowtail=normal in combination with dir=both. That <a href="http://magjac.com/graphviz-visual-editor/?dot=digraph%20so%20%7B%0D%0A%20%20%20%20%2F%2F%20This%20fails%0D%0A%20%20%20%20i%3As%20-%3E%20j%20%5Blabel%3D%22Reverse%20direction%5Cn%20%2B%20port%20choice%5Cn%20%2B%20rank%3Dsame%22%2C%20dir%3D%22back%22%5D%0D%0A%20%20%20%20%7Brank%3Dsame%20i%3B%20j%7D%0D%0A%20%20%20%20%0D%0A%20%20%20%20%2F%2F%20This%20fails%0D%0A%20%20%20%20k%3As%20-%3E%20l%20%5Blabel%3D%22Reverse%20direction%5Cn%20%2B%20port%20choice%5Cn%20%2B%20rank%3Dsame%5Cn%20%2B%20arrowhead%2Ftail%22%2C%20arrowhead%3Dnone%2C%20arrowtail%3Dnormal%2C%20dir%3D%22both%22%5D%0D%0A%20%20%20%20%7Brank%3Dsame%20k%3B%20l%7D%0D%0A%7D" rel="nofollow noreferrer">didn't work either and somehow even affects the  i -> j edge as well.

digraph so {
    // This fails
    i:s -> j [label="Reverse direction\n + port choice\n + rank=same", dir="back"]
    {rank=same i; j}

    // This fails
    k:s -> l [label="Reverse direction\n + port choice\n + rank=same\n + arrowhead/tail", arrowhead=none, arrowtail=normal, dir="both"]
    {rank=same k; l}
}

Body:
I found that mentioning the dir attribute before the label attribute gets you what you want:

digraph so {
    i:s -> j [dir="back", label="Reverse direction\n + port choice\n + rank=same"]
    {rank=same; i;j}
}


问:
Regex search pattern to extract string with 2 words limit
Looking to build some pattern using my_string as starting point to extract from my_string till Inc. i.e. Papa Johns some_text Inc

my_string_1 = 'Papa Johns'

my_string_1 = 'Inc.'

Need to search in any of the below sentences.

sent_1 = The company Papa Johns Retail Chain Inc. sells pizza, pastas etc.

sent_2 = The company Papa Johns Retail Chain., Inc. sells pizza, pastas etc.

sent_3 = The company Papa Johns Retail Chain, Inc. sells pizza, pastas etc.

sent_4 = The company Papa Johns Retail., Chain, Inc. sells pizza, pastas etc.

sent_5 = The company Papa Johns Retail, Inc. sells pizza, pastas etc.

I built a pattern pattern = '''Papa Johns (.{,30})Inc.''' and also this is working fine.

Is this possible if I do not use 30 chars condition but use 2 words limit (may be space split) to extract the required for all sentences.

答:
You could use the pattern:

\bPapa Johns(?: \S+){0,2} Inc\.
```
<p>This matches <code>Papa Johns ... Inc.</code> with at most 2 words in between.</p>
<p>Python script:</p>
```inp = ["The company Papa Johns Retail Chain Inc. sells pizza, pastas etc.", "The company Papa Johns New Retail Chain Inc. sells pizza, pastas etc."]
for i in inp:
    if re.search(r'\bPapa Johns(?: \S+){0,2} Inc\.', i):
        print("MATCH:    " + i)
    else:
        print("NO MATCH: " + i)
```
<p>This prints:</p>
```MATCH:    The company Papa Johns Retail Chain Inc. sells pizza, pastas etc.
NO MATCH: The company Papa Johns New Retail Chain Inc. sells pizza, pastas etc.
```

Body:
You could use the pattern:

\bPapa Johns(?: \S+){0,2} Inc\.

This matches Papa Johns ... Inc. with at most 2 words in between.

Python script:

inp = ["The company Papa Johns Retail Chain Inc. sells pizza, pastas etc.", "The company Papa Johns New Retail Chain Inc. sells pizza, pastas etc."]
for i in inp:
    if re.search(r'\bPapa Johns(?: \S+){0,2} Inc\.', i):
        print("MATCH:    " + i)
    else:
        print("NO MATCH: " + i)

This prints:

MATCH:    The company Papa Johns Retail Chain Inc. sells pizza, pastas etc.
NO MATCH: The company Papa Johns New Retail Chain Inc. sells pizza, pastas etc.


问:
Why im getting this error Warning: Operand of null-aware operation '??' has type 'String' which excludes null. Dart Language
so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get
: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
String ``userName = name ?? "Guest User";

My Code is

```<code>void learnCondExpr() {
 String name = 'Yamix';

 String userName = name ?? "Guest User";
 print(userName);
}
</code>```

can i get some help please :)

答:
So ?? operation must be put after a nullable variable.
But in your code name variable is String, not nullable.
So ?? "Guest User" is always ignored.
The warning is saying about that - this code is useless.

P.S.
If you fix code to String? name = 'Yamix';, the warning will go away.

Body:
so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get
: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
String ``userName = name ?? "Guest User";

My Code is

void learnCondExpr() {
 String name = 'Yamix';

 String userName = name ?? "Guest User";
 print(userName);
}

can i get some help please :)