问:
MySQL denies access with correct credentials (Zabbix 4.0)
I've installed Zabbix 4.0 on Apache2 with a MySQL database. I have created a user called zabbix with a password zabbix, and followed the instructions here.

I can log into MySql via the CLI as user zabbix and write to the tables in the zabbix database - which means, my credentials are good.

My Zabbix configuration file looks like this:

```<code><?php
// Zabbix GUI configuration file.
global $DB;

$DB['TYPE']       = 'MYSQL';
$DB['SERVER']     = 'localhost';
$DB['PORT']       = '3306';
$DB['DATABASE']   = 'zabbix';
$DB['USER']       = 'zabbix';
$DB['PASSWORD']   = 'zabbix';

// Schema name. Used for IBM DB2 and PostgresSQL.
$DB['SCHEMA'] = '';

$ZBX_SERVER       = '192.168.0.100';
$ZBX_SERVER_PORT  = '10051';
$ZBX_SERVER_NAME  = 'Test';

$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;
</code>```

The zabbix_server.log shows

```<code>1296:20200214:070924.785 database is down: reconnecting in 10 seconds
1296:20200214:070934.786 [Z3001] connection to database 'zabbix' failed: [1045] Access denied for user 'zabbix'@'localhost' (using password: YES)`
</code>```

which would indicate the permissions are wrong.

The error.log in MySQL shows the same:

```<code>2020-02-14T07:10:14.791188Z 13 [Note] Access denied for user 'zabbix'@'localhost' (using password: YES)
</code>```

I have tried:

Changing the password

Created a new user and granted it all privileges

Checked for the anonymous ' ' user (it's not there)

Changing the port (0 is the default, tried changing the MySql port to 3000, 3500, 3306)

Got rid of the 127.0.1.1 entry in my /etc/hosts

Changed the $DB['SERVER'] to 127.0.0.1 and 192.168.0.100

Reinstalled everything from scratch, including Ubuntu and LAMP - and I got to the exact same error.

What else could it be? It's a plain error message that the credentials are wrong. It's just that they are not wrong.

Versions:

mysql -V shows Ver 14.14 Distrib 5.7.29, for Linux (x86_64) using  EditLine wrapper

zabbix_server --version shows zabbix_server (Zabbix) 4.0.17
Revision a528a0a4bc 28 January 2020, compilation time: Jan 30 2020 10:22:22

Running on Ubuntu 18.04.4 LTS

EDIT

```<code>mysql> show grants for 'zabbix'@'localhost';
+------------------------------------------------------------+
| Grants for zabbix@localhost                                |
+------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'zabbix'@'localhost'                 |
| GRANT ALL PRIVILEGES ON `zabbix`.* TO 'zabbix'@'localhost' |
+------------------------------------------------------------+
2 rows in set (0.00 sec)
</code>```

答:
Truth is I never used Zabbix but I checked a few solutions online and I see the most common possibility considering all the things you tried already, would be that during setup you entered the wrong version number.

At the point for creating the credentials, ensure you have the correct version of the zabbix-server

```<code>zcat /usr/share/doc/zabbix-server-mysql-3.4.4/create.sql.gz | mysql zabbix -uzabbix -p
</code>```

here is a link that might help.
https://www.zabbix.com/forum/zabbix-help/52154-zabbix-cannot-connect-to-the-database?t=59755

https://support.zabbix.com/browse/ZBX-13057

I am not the one with the problem but I feel so much on edge. I hate these kind of errors. They are frustrating.

Body:
I've installed Zabbix 4.0 on Apache2 with a MySQL database. I have created a user called zabbix with a password zabbix, and followed the instructions here.

I can log into MySql via the CLI as user zabbix and write to the tables in the zabbix database - which means, my credentials are good.

My Zabbix configuration file looks like this:

<?php
// Zabbix GUI configuration file.
global $DB;

$DB['TYPE']       = 'MYSQL';
$DB['SERVER']     = 'localhost';
$DB['PORT']       = '3306';
$DB['DATABASE']   = 'zabbix';
$DB['USER']       = 'zabbix';
$DB['PASSWORD']   = 'zabbix';

// Schema name. Used for IBM DB2 and PostgresSQL.
$DB['SCHEMA'] = '';

$ZBX_SERVER       = '192.168.0.100';
$ZBX_SERVER_PORT  = '10051';
$ZBX_SERVER_NAME  = 'Test';

$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;

The zabbix_server.log shows

1296:20200214:070924.785 database is down: reconnecting in 10 seconds
1296:20200214:070934.786 [Z3001] connection to database 'zabbix' failed: [1045] Access denied for user 'zabbix'@'localhost' (using password: YES)`

which would indicate the permissions are wrong.

The error.log in MySQL shows the same:

2020-02-14T07:10:14.791188Z 13 [Note] Access denied for user 'zabbix'@'localhost' (using password: YES)

I have tried:

Changing the password

Created a new user and granted it all privileges

Checked for the anonymous ' ' user (it's not there)

Changing the port (0 is the default, tried changing the MySql port to 3000, 3500, 3306)

Got rid of the 127.0.1.1 entry in my /etc/hosts

Changed the $DB['SERVER'] to 127.0.0.1 and 192.168.0.100

Reinstalled everything from scratch, including Ubuntu and LAMP - and I got to the exact same error.

What else could it be? It's a plain error message that the credentials are wrong. It's just that they are not wrong.

Versions:

mysql -V shows Ver 14.14 Distrib 5.7.29, for Linux (x86_64) using  EditLine wrapper

zabbix_server --version shows zabbix_server (Zabbix) 4.0.17
Revision a528a0a4bc 28 January 2020, compilation time: Jan 30 2020 10:22:22

Running on Ubuntu 18.04.4 LTS

EDIT

mysql> show grants for 'zabbix'@'localhost';
+------------------------------------------------------------+
| Grants for zabbix@localhost                                |
+------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'zabbix'@'localhost'                 |
| GRANT ALL PRIVILEGES ON `zabbix`.* TO 'zabbix'@'localhost' |
+------------------------------------------------------------+
2 rows in set (0.00 sec)

Body:
Truth is I never used Zabbix but I checked a few solutions online and I see the most common possibility considering all the things you tried already, would be that during setup you entered the wrong version number.

At the point for creating the credentials, ensure you have the correct version of the zabbix-server

zcat /usr/share/doc/zabbix-server-mysql-3.4.4/create.sql.gz | mysql zabbix -uzabbix -p

here is a link that might help.
https://www.zabbix.com/forum/zabbix-help/52154-zabbix-cannot-connect-to-the-database?t=59755

https://support.zabbix.com/browse/ZBX-13057

I am not the one with the problem but I feel so much on edge. I hate these kind of errors. They are frustrating.


来源: stackexchange

问:
How to resolve AttributeError: 'DataFrame' object has no attribute
I know that this kind of question was asked before and I've checked all the answers and I have tried several times to find a solution but in vain.
In fact I call a Dataframe using Pandas. I've uploaded a csv.file.

When I type data.Country and data.Year, I get the 1st Column and the second one displayed. However when I type data.Number, everytime it gives me this error:

AttributeError: 'DataFrame' object has no attribute 'Number'.

答:
I'd like to make it simple for you.
the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is   " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write
data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip()
but the chances are that it will throw the same error in particular in some cases after the query.
changing name in excel sheet will work definitely.</p>

ContentLicense: CC BY-SA 4.0


问:
How to update status in DataTable listing page in Laravel
I need without refresh listing page update status of record. I have tried it with full page refresh but I want to an AJAX feature with Laravel rules.</p>

答:
If you like to update a record with Ajax you have to implement Ajax in your template and request a controller method that execute the change.

jQuery example:

```<code>$.ajax({
    type: "POST",
    url: '/pageController/updateStatus',
    data: {id: 15, status: 'example'},
    success: function(response) { // Change elements in the DOM },
});
</code>```

This will post the page ID and status to the updateStatus controller method. On success you can update values in the DOM.

Controller example:

```<code>class PageController {
    public function updateStatus(int $id, $status) {
        $page = Page::findOrFail($id);
        $page->status = $status;
        $page->save();

        return $page->status;
    }
}
</code>```

In the controller you search for the given ID in the Page model. Then you update the status, save it, and return the new status so you can use it in the front-end.

Body:
If you like to update a record with Ajax you have to implement Ajax in your template and request a controller method that execute the change.

jQuery example:

$.ajax({
    type: "POST",
    url: '/pageController/updateStatus',
    data: {id: 15, status: 'example'},
    success: function(response) { // Change elements in the DOM },
});

This will post the page ID and status to the updateStatus controller method. On success you can update values in the DOM.

Controller example:

class PageController {
    public function updateStatus(int $id, $status) {
        $page = Page::findOrFail($id);
        $page->status = $status;
        $page->save();

        return $page->status;
    }
}

In the controller you search for the given ID in the Page model. Then you update the status, save it, and return the new status so you can use it in the front-end.


问:
JAXB - How to define mapped class to generate node text value
I have classes defined as:

```<code>@XmlRootElement( name = "RootNode" )
public class RootNode{
.....
    @XmlElement( name = "code", required = true )
    protected CodeWord code;

    @XmlElement( name = "text" )
    protected EncText text;
.....
}
</code>```

While class EncText looks like:

```<code>@XmlType( name = "EncText ",
        propOrder = {
                "language"
        } )
public class EncText {
.....
    @XmlElement( name = "language" )
    protected LANG language;

    @XmlAttribute( name = "mediaType" )
    @XmlJavaTypeAdapter( CollapsedStringAdapter.class )
    protected String mediaType;
.....
}
</code>```

In the EncText, I might have text data which need to be added as the text node. I would like to have output, after marshalling, like:

```<code><RootNode>
    <text mediaType="plain/text">
        Data come from database.
    </text>
</RootNode>
</code>```

How can I define property in, say EncText, as well proper setter and getter to allow me to do so? I tried to define a @XmlValue property in EncText. However, error showed that XmlElement can not coexist with XmlValue. I need advices for this. Thanks a lot.

答:
I tried to define a @XmlValue property in EncText.

That should have worked fine, but since you didn't show what you tried, here's how:

```<code>@XmlRootElement( name = "RootNode" )
class RootNode {
    @XmlElement( name = "text" )
    protected EncText text;
}
</code>```

```<code>class EncText {
    @XmlAttribute( name = "mediaType" )
    protected String mediaType;

    @XmlValue
    protected String textValue;
}
</code>```

Test

```<code>RootNode rootNode = new RootNode();
rootNode.text = new EncText();
rootNode.text.mediaType = "plain/text";
rootNode.text.textValue = "Data come from database.";

JAXBContext jaxbContext = JAXBContext.newInstance(RootNode.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rootNode, System.out);
</code>```

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootNode>
    <text mediaType="plain/text">Data come from database.</text>
</RootNode>
```

Body:
I have classes defined as:

@XmlRootElement( name = "RootNode" )
public class RootNode{
.....
    @XmlElement( name = "code", required = true )
    protected CodeWord code;

    @XmlElement( name = "text" )
    protected EncText text;
.....
}

While class EncText looks like:

@XmlType( name = "EncText ",
        propOrder = {
                "language"
        } )
public class EncText {
.....
    @XmlElement( name = "language" )
    protected LANG language;

    @XmlAttribute( name = "mediaType" )
    @XmlJavaTypeAdapter( CollapsedStringAdapter.class )
    protected String mediaType;
.....
}

In the EncText, I might have text data which need to be added as the text node. I would like to have output, after marshalling, like:

<RootNode>
    <text mediaType="plain/text">
        Data come from database.
    </text>
</RootNode>

How can I define property in, say EncText, as well proper setter and getter to allow me to do so? I tried to define a @XmlValue property in EncText. However, error showed that XmlElement can not coexist with XmlValue. I need advices for this. Thanks a lot.

Body:
I tried to define a @XmlValue property in EncText.

That should have worked fine, but since you didn't show what you tried, here's how:

@XmlRootElement( name = "RootNode" )
class RootNode {
    @XmlElement( name = "text" )
    protected EncText text;
}

class EncText {
    @XmlAttribute( name = "mediaType" )
    protected String mediaType;

    @XmlValue
    protected String textValue;
}

Test

RootNode rootNode = new RootNode();
rootNode.text = new EncText();
rootNode.text.mediaType = "plain/text";
rootNode.text.textValue = "Data come from database.";

JAXBContext jaxbContext = JAXBContext.newInstance(RootNode.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rootNode, System.out);

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootNode>
    <text mediaType="plain/text">Data come from database.</text>
</RootNode>


问:
how to write a unittest for a class?
```<code>class Hand:

def __init__(self,cards, total, soft_ace_count):
    self.cards = cards
    self.total = total
    self.soft_ace_count = soft_ace_count

def __str__(self):
    return(str(self.cards)+','+str(self.total)+','+str(self.soft_ace_count))

def add_card(self):
    self.cards.append(get_card())
    self.score()

def is_blackjack(self):
    return len(self.cards)==2 and self.total==21

def is_bust(self):
    return self.total > 21

def score(self):
    self.total=0
    self.soft_ace_count=0

    for x in self.cards:
        if x > 10:
            x=10
        self.total+=x

    #the following code will decide 1 =11 or 1 = 1
    if self.total <= 11 and 1 in self.cards:
        self.total+=10
        self.soft_ace_count+=1
</code>```

I am trying to write the unittest for this 'Hand' class. Do I need a init setup for this particular unittest?
Here is part of code of my unittest. Thank you so much if anyone could help me with this. I just started in python. Any suggestions would help. Thank you. Neglect the indent

```<code>class hand(unittest.TestCase):

def __init__(self):
    self.cards=cards
    self.total = total
    self.soft_ace_count = soft_ace_count
</code>```

答:
Assuming that you have your class in a module named hand.py, you can place your unittest script in the same directory. It could look like this:

```<code>import unittest
from hand import Hand

class hand(unittest.TestCase):

    def test_init(self):
        cards = []
        h = Hand(cards, 0, 0)
        self.assertEqual(h.total, 0)
        self.assertEqual(h.soft_ace_count, 0)
        self.assertEqual(len(h.cards), 0)

    # def test_blackjack(self):
        #....

    # def test_score(self):
        #....

    # def test_OTHERTHINGS(self):
        #.....

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

if you name your unittestscript for example unittesthand.py, you can run it via "python unittestscript.py". You will get the following result:

```<code>> .
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code>```

The unittest component has executed all methods starting with "test" and executed. In the example the "test_init" method. This is NOT the initialization of the test, but the unittest for the initialization of class Hand.

Now change for example the code to "self.assertEqual(h.total, 1)", and you will see that the unittest component reports an error.

Now you can create additional cases for the other methods.You can also create a base test case with code that is always executed before and after the unittests and so on...

Title: how to write a unittest for a class?

Body:
class Hand:

def __init__(self,cards, total, soft_ace_count):
    self.cards = cards
    self.total = total
    self.soft_ace_count = soft_ace_count

def __str__(self):
    return(str(self.cards)+','+str(self.total)+','+str(self.soft_ace_count))

def add_card(self):
    self.cards.append(get_card())
    self.score()

def is_blackjack(self):
    return len(self.cards)==2 and self.total==21

def is_bust(self):
    return self.total > 21

def score(self):
    self.total=0
    self.soft_ace_count=0

    for x in self.cards:
        if x > 10:
            x=10
        self.total+=x

    #the following code will decide 1 =11 or 1 = 1
    if self.total <= 11 and 1 in self.cards:
        self.total+=10
        self.soft_ace_count+=1

I am trying to write the unittest for this 'Hand' class. Do I need a init setup for this particular unittest?
Here is part of code of my unittest. Thank you so much if anyone could help me with this. I just started in python. Any suggestions would help. Thank you. Neglect the indent

class hand(unittest.TestCase):

def __init__(self):
    self.cards=cards
    self.total = total
    self.soft_ace_count = soft_ace_count

Body:
Assuming that you have your class in a module named hand.py, you can place your unittest script in the same directory. It could look like this:

import unittest
from hand import Hand

class hand(unittest.TestCase):

    def test_init(self):
        cards = []
        h = Hand(cards, 0, 0)
        self.assertEqual(h.total, 0)
        self.assertEqual(h.soft_ace_count, 0)
        self.assertEqual(len(h.cards), 0)

    # def test_blackjack(self):
        #....

    # def test_score(self):
        #....

    # def test_OTHERTHINGS(self):
        #.....

if __name__ == '__main__':
    unittest.main()

if you name your unittestscript for example unittesthand.py, you can run it via "python unittestscript.py". You will get the following result:

> .
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

The unittest component has executed all methods starting with "test" and executed. In the example the "test_init" method. This is NOT the initialization of the test, but the unittest for the initialization of class Hand.

Now change for example the code to "self.assertEqual(h.total, 1)", and you will see that the unittest component reports an error.

Now you can create additional cases for the other methods.You can also create a base test case with code that is always executed before and after the unittests and so on...


问:
How to install ffmpeg in a docker container
I'm using aeneas python module which uses ffmpeg. I install ffmpeg in the dockerfile as follows:

```<code>RUN apt-get update && apt-get install -y ffmpeg
</code>```

Now when I run the program, it fails with:

aeneas.ffprobewrapper.FFPROBEPathError: Unable to call the 'ffprobe' ffprobe executable : [Errno 2] No such file or directory: 'ffprobe'

and

aeneas.audiofile.AudioFileProbeError: Unable to call ffprobe executable

So my question is, how can I successfully use ffmpeg in a docker container? I'm running Ubuntu 16.04.

答:
Install fresh ffmpeg version from sources in docker container on Debian 9/10/Ubuntu.

You can replace 4.2.2 version to any other available on https://ffmpeg.org/releases/

# Compile and install fresh ffmpeg from sources:
# See: https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu
RUN apt-get update -qq && apt-get -y install \
      autoconf \
      automake \
      build-essential \
      cmake \
      git-core \
      libass-dev \
      libfreetype6-dev \
      libsdl2-dev \
      libtool \
      libva-dev \
      libvdpau-dev \
      libvorbis-dev \
      libxcb1-dev \
      libxcb-shm0-dev \
      libxcb-xfixes0-dev \
      pkg-config \
      texinfo \
      wget \
      zlib1g-dev \
      nasm \
      yasm \
      libx265-dev \
      libnuma-dev \
      libvpx-dev \
      libmp3lame-dev \
      libopus-dev \
      libx264-dev \
      libfdk-aac-dev
RUN mkdir -p ~/ffmpeg_sources ~/bin && cd ~/ffmpeg_sources && \
    wget -O ffmpeg-4.2.2.tar.bz2 https://ffmpeg.org/releases/ffmpeg-4.2.2.tar.bz2 && \
    tar xjvf ffmpeg-4.2.2.tar.bz2 && \
    cd ffmpeg-4.2.2 && \
    PATH="$HOME/bin:$PATH" PKG_CONFIG_PATH="$HOME/ffmpeg_build/lib/pkgconfig" ./configure \
      --prefix="$HOME/ffmpeg_build" \
      --pkg-config-flags="--static" \
      --extra-cflags="-I$HOME/ffmpeg_build/include" \
      --extra-ldflags="-L$HOME/ffmpeg_build/lib" \
      --extra-libs="-lpthread -lm" \
      --bindir="$HOME/bin" \
      --enable-libfdk-aac \
      --enable-gpl \
      --enable-libass \
      --enable-libfreetype \
      --enable-libmp3lame \
      --enable-libopus \
      --enable-libvorbis \
      --enable-libvpx \
      --enable-libx264 \
      --enable-libx265 \
      --enable-nonfree && \
    PATH="$HOME/bin:$PATH" make -j8 && \
    make install -j8 && \
    hash -r
RUN mv ~/bin/ffmpeg /usr/local/bin && mv ~/bin/ffprobe /usr/local/bin && mv ~/bin/ffplay /usr/local/bin
```

Body:
I'm using aeneas python module which uses ffmpeg. I install ffmpeg in the dockerfile as follows:

RUN apt-get update && apt-get install -y ffmpeg

Now when I run the program, it fails with:

aeneas.ffprobewrapper.FFPROBEPathError: Unable to call the 'ffprobe' ffprobe executable : [Errno 2] No such file or directory: 'ffprobe'

and

aeneas.audiofile.AudioFileProbeError: Unable to call ffprobe executable

So my question is, how can I successfully use ffmpeg in a docker container? I'm running Ubuntu 16.04.


问:
Responsive Table Break
I have a website that is connected to a database. The website has a table that pulls out the values from the database. I want this table to be responsive. I have almost got it to work except one part. Everything is showing and working except for the titles(Band Name, City, Role, Style, SKill). They wont show. I think it has something to do with the last CSS code (content attribute). If someone has experience or can help out, I would highly appreciate it! Take a look at the photo to to see what I mean

screenshot from problem

.table td,
.table th {
  padding: 12px 15px;
  border: 1px solid #ddd;
  text-align: center;
  font-size: 16px;
}

.table tbody tr:nth-child(even) {
  background-color: #e7e7e7;
}

@media(max-width: 500px) {
  .table thead {
    display: none;
  }
  .table,
  .table tbody,
  .table tr,
  .table td {
    display: block;
    width: 100%;
  }
  .table tr {
    margin-bottom: 15px;
  }
  .table td {
    text-align: right;
    padding-left: 50%;
    text-align: right;
    position: relative;
  }
  .table th::before {
    content: attr(scope);
    position: absolute;
    left: 0;
    width: 50%;
    padding-left: 15px;
    font-size: 15px;
    font-weight: bold;
    text-align: left;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="band-finder-table">
  <table class="table">
    <thead class="thead-dark">
      <tr>
        <th scope="col">Band Name</th>
        <th scope="col">City</th>
        <th scope="col">Role</th>
        <th scope="col">Style</th>
        <th scope="col">Skill</th>
        <th scope="col"></th>
        <th scope="col"></th>
      </tr>
    </thead>
    <tbody>
      <tr th:each="band : ${bands}">
        <td th:text="${band.bandName}">Band Name</td>
        <td th:text="${band.city}">City</td>
        <td th:text="${band.role.roleName}">Role Name</td>
        <td th:text="${band.style.styleName}">style Name</td>
        <td th:text="${band.skill.level}">Level</td>
        <td>Edit</td>
        <td>Remove</td>
      </tr>
    </tbody>
  </table></code>```

答:
I got the help of a friend to answer this question
The code that had to be changed is: </p>

```<code> HTML:
 <td data-label="Band Name"th:text="${band.bandName}">Band Name</td>
</code>```

<p>And </p>

```<code> CSS:
 .table td::before{
  content: attr(data-label);
</code>```

Title: Responsive Table Break

Body:
I have a website that is connected to a database. The website has a table that pulls out the values from the database. I want this table to be responsive. I have almost got it to work except one part. Everything is showing and working except for the titles(Band Name, City, Role, Style, SKill). They wont show. I think it has something to do with the last CSS code (content attribute). If someone has experience or can help out, I would highly appreciate it! Take a look at the photo to to see what I mean

screenshot from problem

.table td,
.table th {
  padding: 12px 15px;
  border: 1px solid #ddd;
  text-align: center;
  font-size: 16px;
}

.table tbody tr:nth-child(even) {
  background-color: #e7e7e7;
}

@media(max-width: 500px) {
  .table thead {
    display: none;
  }
  .table,
  .table tbody,
  .table tr,
  .table td {
    display: block;
    width: 100%;
  }
  .table tr {
    margin-bottom: 15px;
  }
  .table td {
    text-align: right;
    padding-left: 50%;
    text-align: right;
    position: relative;
  }
  .table th::before {
    content: attr(scope);
    position: absolute;
    left: 0;
    width: 50%;
    padding-left: 15px;
    font-size: 15px;
    font-weight: bold;
    text-align: left;
  }
}

        Band Name
        City
        Role
        Style
        Skill

        Band Name
        City
        Role Name
        style Name
        Level
        Edit
        Remove

Body:
I got the help of a friend to answer this question
The code that had to be changed is:

 HTML:
 <td data-label="Band Name"th:text="${band.bandName}">Band Name</td>

And

 CSS:
 .table td::before{
  content: attr(data-label);


问:
Any way to shorten dict(a=a)?
I have a long list of long variable names that I need to pack into a dictionary - so my code can end up looking like this:

configs = dict(
    long_variable_name_1=long_variable_name_1,
    not_longest_variable_name_3=not_longest_variable_name_3,
    longer_variable_name_2=longer_variable_name_2,
    # ...
)
```

<p>Instead of saying "this equals this", can we make a function <code>magic_fn</code> that takes just "this" and returns <code>dict(this=this)</code>? i.e. <code>magic_fn(a, b) == dict(a=a, b=b)</code></p>

<p>From an information standpoint, <code>dict(a=a)</code> involves a redundancy, since <code>magic_fn</code> can take just one <code>a</code> and do the <code>a=a</code> internally. I understand this isn't how a Python dict works, and that left <code>a</code> is a key, etc. - but maybe there's some trickery to be exploited from builtins and metafunctions.</p>

<hr>

<p><strong>Update</strong>: none of the answers in other questions accomplish what I seek, nor ask exactly what I ask; my goal is to shorten the <code>stuff=stuff</code> syntax with local variables <em>in-scope</em> - no user input, etc.</p>

<hr>

<p><strong>My answer</strong>:</p>

<pre class="lang-py prettyprint-override"><code>def to_dict(var_str):
    while " " in var_str:  # trim all spaces
        var_str = var_str.replace(" ", "")
    return {name:eval("%s" % name) for name in var_str.split(",")}
</code>```

```<code># USAGE
a = 1; b = 2; c = 3
print(to_dict("a, b, c"))  # {'a': 1, 'b': 2, 'c': 3}
</code>```

Must be defined in the same file it's used (cannot be imported). See other caveats in comments.

答:
Using eval, we can get a dictionary of string representations of all the variables whose names are in a list.

```<code>def var_dict(var_str):
    return {i:eval("%s"%i) for i in var_str.split()}
</code>```

We try it out:

a = '1=2'
b = '2'
c = 4
d = [1,2,'3']

var_dict(var_str='a b c d')
#> {'a': '1=2', 'b': '2', 'c': 4, 'd': [1, 2, '3']}
```

<p>There is one <strong>caveat</strong> about this technique: You need to provide a list of variable names as strings <code>['a','b','c']</code> and not just <code>[a,b,c]</code>. I believe this is not much of an issue since you just want to avoid writing the long variable names multiple times. </p>

<hr>

<p>If you're worried about using <code>eval</code>, you can encapsulate the code being run in an <code>f-string</code>, thus ensuring that only the existing variables will be executed, and so avoiding code injection:</p>

```def var_dict(var_str):
    return {i:eval("f'{%s}"%i) for i in var_str.split()}
var_dict(['a b c d'])
#> {'a': '1=2', 'b': '2', 'c': '4', 'd': "[1, 2, '3']"}

var_dict(['a=1','b','c','d'])  # Would've set a=1 in the previous code
#> ERROR! there is no variable named 'a=1'
```

Note that in this case all returned values are turned into strings (this is the best solution if you are working only with strings or if you were already planning to convert all variables to strings later on).

Title: Any way to shorten dict(a=a)?

Body:
I have a long list of long variable names that I need to pack into a dictionary - so my code can end up looking like this:

configs = dict(
    long_variable_name_1=long_variable_name_1,
    not_longest_variable_name_3=not_longest_variable_name_3,
    longer_variable_name_2=longer_variable_name_2,
    # ...
)

Instead of saying "this equals this", can we make a function magic_fn that takes just "this" and returns dict(this=this)? i.e. magic_fn(a, b) == dict(a=a, b=b)

From an information standpoint, dict(a=a) involves a redundancy, since magic_fn can take just one a and do the a=a internally. I understand this isn't how a Python dict works, and that left a is a key, etc. - but maybe there's some trickery to be exploited from builtins and metafunctions.

Update: none of the answers in other questions accomplish what I seek, nor ask exactly what I ask; my goal is to shorten the stuff=stuff syntax with local variables in-scope - no user input, etc.

My answer:

def to_dict(var_str):
    while " " in var_str:  # trim all spaces
        var_str = var_str.replace(" ", "")
    return {name:eval("%s" % name) for name in var_str.split(",")}

# USAGE
a = 1; b = 2; c = 3
print(to_dict("a, b, c"))  # {'a': 1, 'b': 2, 'c': 3}

Must be defined in the same file it's used (cannot be imported). See other caveats in comments.

Body:
Using eval, we can get a dictionary of string representations of all the variables whose names are in a list.

def var_dict(var_str):
    return {i:eval("%s"%i) for i in var_str.split()}

We try it out:

a = '1=2'
b = '2'
c = 4
d = [1,2,'3']

var_dict(var_str='a b c d')
#> {'a': '1=2', 'b': '2', 'c': 4, 'd': [1, 2, '3']}

There is one caveat about this technique: You need to provide a list of variable names as strings ['a','b','c'] and not just [a,b,c]. I believe this is not much of an issue since you just want to avoid writing the long variable names multiple times.

If you're worried about using eval, you can encapsulate the code being run in an f-string, thus ensuring that only the existing variables will be executed, and so avoiding code injection:

def var_dict(var_str):
    return {i:eval("f'{%s}"%i) for i in var_str.split()}
var_dict(['a b c d'])
#> {'a': '1=2', 'b': '2', 'c': '4', 'd': "[1, 2, '3']"}

var_dict(['a=1','b','c','d'])  # Would've set a=1 in the previous code
#> ERROR! there is no variable named 'a=1'

Note that in this case all returned values are turned into strings (this is the best solution if you are working only with strings or if you were already planning to convert all variables to strings later on).


问:
Python - Create a new sublist between two elements in an ordered list
Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

```<code>begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]
</code>```

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?

EDIT:
There were two working solutions to this.

```<code>rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]
</code>```

Which is obscenely complicated compared to:

```<code>if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]
</code>```

答:
Maybe this?</p>

```<code>new_right = right[begin: end + 1] if end > begin else right[begin:] + right[:end + 1]
</code>```

Body:
Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?

EDIT:
There were two working solutions to this.

rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]

Which is obscenely complicated compared to:

if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]

Body:
Maybe this?

new_right = right[begin: end + 1] if end > begin else right[begin:] + right[:end + 1]


问:
How to read out an .rgba16Float MTLTexture via getBytes()
I have problems reading out an MTLTexture which has a pixel format of .rgba16Float, the main reason is that Swift does not seem to have a corresponding SIMD4 format.

For .rgba32Float I can simply use the SIMD4< Float > format, like so

```<code>if let texture = texture {
    let region = MTLRegionMake2D(x, y, 1, 1)

    let texArray = Array<SIMD4<Float>>(repeating: SIMD4<Float>(repeating: 0), count: 1)
    texture.getBytes(UnsafeMutableRawPointer(mutating: texArray), bytesPerRow: (MemoryLayout<SIMD4<Float>>.size * texture.width), from: region, mipmapLevel: 0)
    let value = texArray[0]
}
</code>```

This works fine as the Swift Float data type is 32bit, how can I do the same for a 16 bit .rgba16Float texture ?

答:
You can use vImage to convert the buffer from 16-bit to 32-bit float first. Check out vImageConvert_Planar16FtoPlanarF. But not that the documentation on the site is wrong (it's from another function...). I found this utility that demonstrate the process.

It would be more efficient, however, if you could use Metal to convert the texture into 32-bit float (or directly render into a 32-bit texture in the first place).

Body:
I have problems reading out an MTLTexture which has a pixel format of .rgba16Float, the main reason is that Swift does not seem to have a corresponding SIMD4 format.

For .rgba32Float I can simply use the SIMD4< Float > format, like so

if let texture = texture {
    let region = MTLRegionMake2D(x, y, 1, 1)

    let texArray = Array<SIMD4<Float>>(repeating: SIMD4<Float>(repeating: 0), count: 1)
    texture.getBytes(UnsafeMutableRawPointer(mutating: texArray), bytesPerRow: (MemoryLayout<SIMD4<Float>>.size * texture.width), from: region, mipmapLevel: 0)
    let value = texArray[0]
}

This works fine as the Swift Float data type is 32bit, how can I do the same for a 16 bit .rgba16Float texture ?


问:
Desktop Excel hangs when the getSelectedRanges method is called in a workbook where a big range is selected
I am trying to develop an Excel JavaScript add-in that processes all selected ranges.

When selecting a large range with data, such as A1:O1000000, desktop Excel hangs when I call the ctx.sync method after getting the ctx.workbook.getSelectedRanges() object.

Also the problem is reproduced in Excel 2016 and Excel 2019 desktop versions.
In Excel Online (web), this code works normally.

My Excel version is 16.0.12430.20172 64-bit

```<code>onTestClick(e)
    {
        console.log("onTestClick");
        Excel.run(function (ctx) {
            let selectedRanges = ctx.workbook.getSelectedRanges();

            selectedRanges.load(["areas", "areaCount", "address", "addressLocal"]);
            selectedRanges.areas.load({ $all: false, address: true,  addressLocal: true});

            return ctx.sync().then(function () {
                for (let index = 0; index < selectedRanges.areaCount; index++) {
                    let area = selectedRanges.areas.items[index];
                    console.log("area[" + index + "] = " + area.address);
                }

            }).catch(function (error) {
                console.log("onTestClick sync error: " + error);
            }).then(()=>{
                console.log("onTestClick end");
            });
        }).catch(function (error) {
            console.log("onTestClick Excel.run error: " + error);
        });
    }
</code>```

答:
In your script above, load "areas" in selectedRanges is not necessary.  You can make some changes on "selectedRanges.load(["areas", "areaCount", "address", "addressLocal"]);" to "selectedRanges.load(["areaCount", "address", "addressLocal"]);" instead. With the change, you can see the result is returned quickly.

The reason is that "areas" is Excel.RangeCollection(https://learn.microsoft.com/en-us/javascript/api/excel/excel.rangecollection?view=excel-js-preview), which returns a collection of rectangular ranges that comprise this RangeAreas object. The return value for Range(A1:O1000000) is too big to be processed.

Body:
I am trying to develop an Excel JavaScript add-in that processes all selected ranges.

When selecting a large range with data, such as A1:O1000000, desktop Excel hangs when I call the ctx.sync method after getting the ctx.workbook.getSelectedRanges() object.

Also the problem is reproduced in Excel 2016 and Excel 2019 desktop versions.
In Excel Online (web), this code works normally.

My Excel version is 16.0.12430.20172 64-bit

onTestClick(e)
    {
        console.log("onTestClick");
        Excel.run(function (ctx) {
            let selectedRanges = ctx.workbook.getSelectedRanges();

            selectedRanges.load(["areas", "areaCount", "address", "addressLocal"]);
            selectedRanges.areas.load({ $all: false, address: true,  addressLocal: true});

            return ctx.sync().then(function () {
                for (let index = 0; index < selectedRanges.areaCount; index++) {
                    let area = selectedRanges.areas.items[index];
                    console.log("area[" + index + "] = " + area.address);
                }

            }).catch(function (error) {
                console.log("onTestClick sync error: " + error);
            }).then(()=>{
                console.log("onTestClick end");
            });
        }).catch(function (error) {
            console.log("onTestClick Excel.run error: " + error);
        });
    }


问:
How to configure dynamic height for UILabel in swift 5?
I am trying to setup UILabel in view controller with dynamic height so that it fits according to the text.

I tried various examples available on stack overflow but to no good yet.

is there any other specific method for Swift 5 to make UILabel height dynamic?

UI Constraints

View Controller

答: Specify numberOfLines = 0 and in label height constraints specify like greater than or equal to zero.</p>


问:
Foreach loop group by XML element value
I want to group them by agent

XML structured as follows

```<code><library>
    <document>
        <ProductName>somename1</ProductName>
        <productAgent>Agent-01</productAgent>
        <productType>Goods</productType>
    </document>
        <ProductName>somename3</ProductName>
        <productAgent>Agent-02</productAgent>
        <productType>Services</productType>
    </document>
    ......
</library>
</code>```

Expecting Output

```<code><ul>
    <li>Agent-01(productAgent)
        <ul>
            <li>somename1 - Goods</li>
        </ul>
    </li>
    <li>Agent-02(productAgent)
        <ul>
            <li>somename3 - Services</li>
            <li>somename6 - Goods</li>
        </ul>
    </li>
</ul>
</code>```

What I tried

```<code><ul>
    <li>Agent-01(productAgent)
        <ul>
            <?php foreach($xml->document as $item){
                if ($item->productAgent == 'Agent-01' ) {
                    echo '<li>'.$item->ProductName.'-'.$item->ProductType.'</li>';
                }
            }
            ?>
        </ul>
    </li>
    <li>Agent-02(productAgent)
        <ul>
            <?php foreach($xml->document as $item){
                if ($item->productAgent == 'Agent-02' ) {
                    echo '<li>'.$item->ProductName.'-'.$item->ProductType.'</li>';
                }
            }
            ?>
        </ul>
    </li>
</ul>
</code>```

Problem

I have to modify my code every time the agent name change. My code doesn't seem to be a good solution when the number of agent increase.

答:
A more complete example with the output...</p>

```<code>//  Build list of product names for each agent
$agents = [];
foreach ( $xml->document as $document ) {
    $agents [(string)$document->productAgent][] = (string)$document->ProductName;
}

?>
<ul>
    <?php // Loop over the agents
           foreach($agents as $name => $agent){  ?>
    <li><?php echo $name; ?>
        <ul>
            <?php // Loop over the the products for the agent
                  foreach($agent as $item){
                echo '<li>'.$item.'</li>';
            }
            ?>
        </ul>
    </li>
    <?php } ?>
</ul>
</code>```

Title: Foreach loop group by XML element value

Body:
I want to group them by agent

XML structured as follows

<library>
    <document>
        <ProductName>somename1</ProductName>
        <productAgent>Agent-01</productAgent>
        <productType>Goods</productType>
    </document>
        <ProductName>somename3</ProductName>
        <productAgent>Agent-02</productAgent>
        <productType>Services</productType>
    </document>
    ......
</library>

Expecting Output

Agent-01(productAgent)

somename1 - Goods

Agent-02(productAgent)

somename3 - Services

somename6 - Goods

What I tried

Agent-01(productAgent)

            <?php foreach($xml->document as $item){
                if ($item->productAgent == 'Agent-01' ) {
                    echo '
'.$item->ProductName.'-'.$item->ProductType.'
';
                }
            }
            ?>

Agent-02(productAgent)

            <?php foreach($xml->document as $item){
                if ($item->productAgent == 'Agent-02' ) {
                    echo '
'.$item->ProductName.'-'.$item->ProductType.'
';
                }
            }
            ?>

Problem

I have to modify my code every time the agent name change. My code doesn't seem to be a good solution when the number of agent increase.

Body:
A more complete example with the output...

//  Build list of product names for each agent
$agents = [];
foreach ( $xml->document as $document ) {
    $agents [(string)$document->productAgent][] = (string)$document->ProductName;
}

?>
<ul>
    <?php // Loop over the agents
           foreach($agents as $name => $agent){  ?>
    <li><?php echo $name; ?>
        <ul>
            <?php // Loop over the the products for the agent
                  foreach($agent as $item){
                echo '<li>'.$item.'</li>';
            }
            ?>
        </ul>
    </li>
    <?php } ?>
</ul>


问:
Tablesorter theme, changing row background on button click
I am using tablesorter 2.0 and I have been trying to override the css theme when a button is clicked, but I can't seem to get anything going.  I tried to add a little css to the theme file, but I think another attribute is overriding it.  What I want to do is change the background color of a row of a certain class.

If anyone can check this out and tell me where to add the class and the attribute to this file, it would be appreciated.

Here is the theme file for tablesorter:

```<code>table.tablesorter {
    font-family:arial;
    background-color: #CDCDCD;
    margin:10px 0pt 15px;
    font-size: 8pt;
    width: 100%;
    text-align: left;
    border-radius:3px;
}
table.tablesorter thead tr th, table.tablesorter tfoot tr th {
    background-color: #e6EEEE;
    border: 1px solid #FFF;
    font-size: 8pt;
    padding: 4px;
}
table.tablesorter thead tr .header {
    background-image: url(bg.gif);
    background-repeat: no-repeat;
    background-position: center right;
    cursor: pointer;
}
table.tablesorter tbody td {
    color: #3D3D3D;
    padding: 4px;
    background-color: #FFF;
    vertical-align: top;
}
table.tablesorter tbody tr.odd td {
    background-color:#F0F0F6;
}
table.tablesorter thead tr .headerSortUp {
    background-image: url(asc.gif);
}
table.tablesorter thead tr .headerSortDown {
    background-image: url(desc.gif);
}
table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
background-color: #5B5781;
}
</code>```

Here is the jquery css I use to change the row (it's a callback from a $.post() call):

```<code>function(){
            $("#row_"+id).css("background-color", "orange");
            }
</code>```

答:
There's nothing wrong with TR having background-color.

Your code works but you have to realize that you specified that TD have a background-color of #FFF. You are changing the TR's BG color, but TD's color is on top of it.

ContentLicense: CC BY-SA 3.0

Body:
I am using tablesorter 2.0 and I have been trying to override the css theme when a button is clicked, but I can't seem to get anything going.  I tried to add a little css to the theme file, but I think another attribute is overriding it.  What I want to do is change the background color of a row of a certain class.

If anyone can check this out and tell me where to add the class and the attribute to this file, it would be appreciated.

Here is the theme file for tablesorter:

table.tablesorter {
    font-family:arial;
    background-color: #CDCDCD;
    margin:10px 0pt 15px;
    font-size: 8pt;
    width: 100%;
    text-align: left;
    border-radius:3px;
}
table.tablesorter thead tr th, table.tablesorter tfoot tr th {
    background-color: #e6EEEE;
    border: 1px solid #FFF;
    font-size: 8pt;
    padding: 4px;
}
table.tablesorter thead tr .header {
    background-image: url(bg.gif);
    background-repeat: no-repeat;
    background-position: center right;
    cursor: pointer;
}
table.tablesorter tbody td {
    color: #3D3D3D;
    padding: 4px;
    background-color: #FFF;
    vertical-align: top;
}
table.tablesorter tbody tr.odd td {
    background-color:#F0F0F6;
}
table.tablesorter thead tr .headerSortUp {
    background-image: url(asc.gif);
}
table.tablesorter thead tr .headerSortDown {
    background-image: url(desc.gif);
}
table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
background-color: #5B5781;
}

Here is the jquery css I use to change the row (it's a callback from a $.post() call):

function(){
            $("#row_"+id).css("background-color", "orange");
            }


问:
How to remove the first weather in weather forecast using weather api
here's the code.

```<code>setWeatherForecast(unit: any, scaleTemp: any) {
    this.forecast.splice(0, this.forecast.length);
    this.weatherService.getLocation().subscribe(data => {
      this.lat = JSON.parse(data['_body']).latitude;
      this.lon = JSON.parse(data['_body']).longitude;

      this.weatherService
        .fiveDayForecast(this.lat, this.lon, unit)
        .subscribe(forecastData => {
          for (let i = 0; i < forecastData.list.length; i = i + 8) {
            console.log(forecastData.list[i]);
            const forecastWeather = new Forecast(
              forecastData.city.name,
              forecastData.list[i].weather[0].description,
              forecastData.list[i].main.temp.toFixed(0) + scaleTemp,
              forecastData.list[i].dt_txt.replace(/\s/, 'T'),
              forecastData.list[i].weather[0].icon
            );
            this.forecast.push(forecastWeather);
          }
          return this.forecast;
        });
    });
  }
</code>```

what I want is to remove the first weather in weather forecast.
for example.

friday, saturday, sunday, monday, tuesday, wednesday

it will remove the saturday. it only display the sunday to tuesday.

答:
```<code>this.forecast.splice(0,1);
</code>```

or

```<code>this.forecast.shift()
</code>```

for more clarification see this link

Now first index removed from your forecast array.

Body:
here's the code.

setWeatherForecast(unit: any, scaleTemp: any) {
    this.forecast.splice(0, this.forecast.length);
    this.weatherService.getLocation().subscribe(data => {
      this.lat = JSON.parse(data['_body']).latitude;
      this.lon = JSON.parse(data['_body']).longitude;

      this.weatherService
        .fiveDayForecast(this.lat, this.lon, unit)
        .subscribe(forecastData => {
          for (let i = 0; i < forecastData.list.length; i = i + 8) {
            console.log(forecastData.list[i]);
            const forecastWeather = new Forecast(
              forecastData.city.name,
              forecastData.list[i].weather[0].description,
              forecastData.list[i].main.temp.toFixed(0) + scaleTemp,
              forecastData.list[i].dt_txt.replace(/\s/, 'T'),
              forecastData.list[i].weather[0].icon
            );
            this.forecast.push(forecastWeather);
          }
          return this.forecast;
        });
    });
  }

what I want is to remove the first weather in weather forecast.
for example.

friday, saturday, sunday, monday, tuesday, wednesday

it will remove the saturday. it only display the sunday to tuesday.

Body:
this.forecast.splice(0,1);

or

this.forecast.shift()

for more clarification see this link

Now first index removed from your forecast array.


问:
Navigate from Fiori List Report to standard app like hot-spot?
I have created List Report Fiori App based on CDS view I've created before. Is there any possibility to use some annotations in existing and/or additional CDS view to create a hotspot smart field on Vendor number?

I.e. when I click on that it will navigate me to standard "Business Partner" App for this vendor?

If this is not possible could you explain how to do it "the other way"?

答:
What you need is called smart-link with intent-based navigation: a link which navigates to business object details by reading its semantic properties aka semantic object.

Semantic object can be defined in two ways:

Through template-based approach, via annotation modeler in Web-IDE. Inside @UI.Lineitem add DataFieldWithIntentBasedNavigation and point it to your field name coming from CDS report

the only difference from this GIF is that you needn't to specify GUI_NAVIGATE property

Through column definition in CDS view

```<code>@Consumption.semanticObject: 'BusinessPartner'
@UI: {
      identification: [{label: 'Vendor No', position: 10}],
      lineItem:[{
        position: 10,
        semanticObjectAction: 'manage',
        type: #WITH_INTENT_BASED_NAVIGATION
        }],
       selectionField.position: 10
     }
</code>```

Semantic object are stored in /UI2/SEMOBJ and /UI2/SEMOBJ_SAP tables, check the correct object before developing.

Body:
What you need is called smart-link with intent-based navigation: a link which navigates to business object details by reading its semantic properties aka semantic object.

Semantic object can be defined in two ways:

Through template-based approach, via annotation modeler in Web-IDE. Inside @UI.Lineitem add DataFieldWithIntentBasedNavigation and point it to your field name coming from CDS report

the only difference from this GIF is that you needn't to specify GUI_NAVIGATE property

Through column definition in CDS view

@Consumption.semanticObject: 'BusinessPartner'
@UI: {
      identification: [{label: 'Vendor No', position: 10}],
      lineItem:[{
        position: 10,
        semanticObjectAction: 'manage',
        type: #WITH_INTENT_BASED_NAVIGATION
        }],
       selectionField.position: 10
     }

Semantic object are stored in /UI2/SEMOBJ and /UI2/SEMOBJ_SAP tables, check the correct object before developing.


问:
Is it bad practice to implement an interface twice?
I'm left clueless in this architectural puzzle and I would love to hear some critisim or suggestions about it.

Situation:

An Entity and Relation both have shared (INode) and unique methods (IEntity or IRelation)

A Class needs to know about both shared and unique methods using either the interface IEntity or IRelation.

Question:

Are the architectures below good or bad practice while trying to program using the S.O.L.I.D & DRY principle?

additional information: the main reason for this question is because in the first diagram (currently implemented) both Entity and Relation implement the INode interface twice.

Situation 1:

Situation 2:

答:
Your diagrams illustrate very well the subtle difference between separation of concerns (conceptual) and interface segregation (class design).

In your case there are not two, but four options:

Your first diagram says that IEntity and IRelation are specialisations of INode.  An IEntity is ALWAYS a INode.  You may write code that processes entities and relations as nodes but there is a reduced reusability: IEntity is coupled to INode, even if it's two different unrelated concepts.

Your second diagram says that IEntity and IRelation are different unrelated things when looking at them through their interface.  Both are now decoupled and usable independently, but you fail to recognize that they have something in common and are thus obliged to deal with them separately.

Another variant would be the solution 1, but without inheritance between interfaces. In this approach you have independent interfaces: IEntity would implement both a general and a specific interface.  Advantage:  you have interface segregation as in 2, but with a better separation of concerns.  The inconvenience is that IEntity may not be self-standing anymore.

Yet another variant (my favourite), would be to split INode in two independent interfaces: a general INamedObject and a specific graph interface  INode.  IEntity and IRelation would then inherit from INamedObject but not from INode.  The advantage is that you have a true separation of concerns:  things are not separated artificially for technical reasons, but according to the concept they represent.

In the end, even if personally I'd advise for option 4, you have to find the right balance for your own design.  Because only you can know how you intend to use your interfaces and classes and the concepts you really want to represent.


问:
Unable to update nested entity using Hibernate JPA
I'm using Hibernate JPA and trying to update nested entity.

Entities:

```<code>@Entity
@Table(name = "profile")
@AllArgsConstructor
@NoArgsConstructor
public class ProfileEntity implements Serializable {

........

    @OneToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name="office_address")
    private AddressEntity officeAddress;
}

@Entity
@Table(name="address")
@AllArgsConstructor
@NoArgsConstructor
public class AddressEntity implements Serializable{

......

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private ProfileEntity userProfile;
}
</code>```

Updating Profile entity with new Address entity

```<code>@Transactional
@Modifying
@Query("update ProfileEntity set officeAddress=:address where userId=:userId")
int updateProfile(
        @Param("userId") Long userId,
        @Param("address") AddressEntity address);
</code>```

Error:

```<code>org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.example.entities.AddressEntity; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.example.entities.AddressEntity
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:436)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    .
    .
    .
    .
</code>```

I understand as the transaction is not committed after a new AddressEntity is inserted, and hibernate is flushing before committing. Thus, it's unable to make an update to ProfileEntity with the new address PK.

But how to fix it ?

I also tried inserting a new AddressEntity and after committing the transaction, updating ProfileEntity, that works. But that's not a good practice, because if ProfileEntity update throws an exception AddressEntity insert should also be rolled back.

答:
I guess address you pass is not present in the database. CascadeType.ALL does not work because of updating by @Query. Cascading is provided for PERSIST, MERGE, REMOVE, REFRESH, DETACH operations only.

Use the following

```<code>@Transactional
public ProfileEntity updateProfile(Long userId, AddressEntity address) {
    ProfileEntity profileEntity = profileEntityRepository.findByUserId(userId);

    profileEntity.setOfficeAddress(address);
    address.setUserProfile(profileEntity);

    return profileEntityRepository.save(profileEntity);
}
</code>```

Body:
I'm using Hibernate JPA and trying to update nested entity.

Entities:

@Entity
@Table(name = "profile")
@AllArgsConstructor
@NoArgsConstructor
public class ProfileEntity implements Serializable {

........

    @OneToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name="office_address")
    private AddressEntity officeAddress;
}

@Entity
@Table(name="address")
@AllArgsConstructor
@NoArgsConstructor
public class AddressEntity implements Serializable{

......

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private ProfileEntity userProfile;
}

Updating Profile entity with new Address entity

@Transactional
@Modifying
@Query("update ProfileEntity set officeAddress=:address where userId=:userId")
int updateProfile(
        @Param("userId") Long userId,
        @Param("address") AddressEntity address);

Error:

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.example.entities.AddressEntity; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.example.entities.AddressEntity
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:436)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    .
    .
    .
    .

I understand as the transaction is not committed after a new AddressEntity is inserted, and hibernate is flushing before committing. Thus, it's unable to make an update to ProfileEntity with the new address PK.

But how to fix it ?

I also tried inserting a new AddressEntity and after committing the transaction, updating ProfileEntity, that works. But that's not a good practice, because if ProfileEntity update throws an exception AddressEntity insert should also be rolled back.

Body:
I guess address you pass is not present in the database. CascadeType.ALL does not work because of updating by @Query. Cascading is provided for PERSIST, MERGE, REMOVE, REFRESH, DETACH operations only.

Use the following

@Transactional
public ProfileEntity updateProfile(Long userId, AddressEntity address) {
    ProfileEntity profileEntity = profileEntityRepository.findByUserId(userId);

    profileEntity.setOfficeAddress(address);
    address.setUserProfile(profileEntity);

    return profileEntityRepository.save(profileEntity);
}


问:
ERROR: audio conversion failed: Unknown encoder 'libmp3lame'
I'm trying to use youtube-dl on a Macbook (using Mojave). It used to work flawlessly but recently I am seeing the following error:

```<code>youtube-dl -x --audio-format mp3 https://youtu.be/somevidR4hhU
[youtube] somevidR4hhU: Downloading webpage
[youtube] somevidR4hhU: Downloading video info webpage
[youtube] somevidR4hhU: Downloading js player vflWnjS_n
[download] Destination: somevidR4hhU.webm
[download] 100% of 4.60MiB in 00:04
[ffmpeg] Destination: somevidR4hhU.mp3
ERROR: audio conversion failed: Unknown encoder 'libmp3lame'
</code>```

I've tried to reinstall youtube-dl and lame with:

```<code>brew reinstall youtube-dl lame
</code>```

but it makes no difference. Any idea what the problem may be?
Thanks in advance!

答:
Homebrew doesn't install the lame.  Compile with libmp3lame:

git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg
cd ffmpeg
./configure --enable-libmp3lame
make
make install
ffmpeg -version
```

That should fix it

Body:
I'm trying to use youtube-dl on a Macbook (using Mojave). It used to work flawlessly but recently I am seeing the following error:

youtube-dl -x --audio-format mp3 https://youtu.be/somevidR4hhU
[youtube] somevidR4hhU: Downloading webpage
[youtube] somevidR4hhU: Downloading video info webpage
[youtube] somevidR4hhU: Downloading js player vflWnjS_n
[download] Destination: somevidR4hhU.webm
[download] 100% of 4.60MiB in 00:04
[ffmpeg] Destination: somevidR4hhU.mp3
ERROR: audio conversion failed: Unknown encoder 'libmp3lame'

I've tried to reinstall youtube-dl and lame with:

brew reinstall youtube-dl lame

but it makes no difference. Any idea what the problem may be?
Thanks in advance!

Body:
Homebrew doesn't install the lame.  Compile with libmp3lame:

git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg
cd ffmpeg
./configure --enable-libmp3lame
make
make install
ffmpeg -version

That should fix it


问:
How do I enable HTTPS on a Cloud Run for Anthos on Google Cloud cluster?
I recently started fiddling with Cloud Run for Anthos on GoogleCloud and I just can't enable HTTPS access. I've followed every step in the docs but it still doesn't work. I have a custom .dev domain which I configured through these steps and everything is fine with HTTP but HTTPS still says connection refused

curl http://api.default.customdomain.dev - works fine

but curl https://api.default.customdomain.dev - says:

curl: (7) Failed to connect to api.default.customdomain.dev port 443: Connection refused

I'm pretty sure there's something not specified in the docs, it happens a lot with GCP docs. Has anyone else struggled with this and might be able to help? Thanks!

EDIT: It was actually my fault - when creating the cert/private key secret I provided default for the --namespace value instead of gke-system. So, yeah... it's fixed now.


问:
Page Redirection
To help better explain my Question, here is what i have:

I am using a Precoded service, on it i have access to the Template HTML Files Only.

The URL to the Login page is : DynamicPage.aspx?Site=Mysite&WebCode=LoginRequired

The Main site URL would look like : DynamicPage.aspx?Site=Mysite&WebCode= or DynamicPage.aspx?Site=Mysite

What i need is a JavaScript I could put into the main header template file that would view "WebCode" And depending on whats entered redirect to a certain page.

I got from "Sitifensys" a code

Sitifensys

if (window.location.href!="foo.bar/login.php") window.location.href="login.php";

The problem with this code is even when i go to the main page it still redirects me to login.php which i do not want it to. I need this code to Read the "WebCode" If it is "LoginRequired" Redirect to "Login.php" else if redirect to "Test.php"

Hope this explanation is a bit better.

答:
Just as answered earlier, you should add a window.location.href="somepage" somewhere.

Some where in your script :

```<code>if (window.location.href!="foo.bar/login.php") window.location.href="login.php";
</code>```

This doesn't need to be in a listener for the page load event.

EDIT :
Regarding your new descriptionn I would use (but would not recommend;)) something like :

```<code>if (location.pathname.indexOf("WebCode=LoginRequired")>0) {
    window.location.href="login.php";
}
</code>```

Hope this will help.

Title: Page Redirection

Body:
Just as answered earlier, you should add a window.location.href="somepage" somewhere.

Some where in your script :

if (window.location.href!="foo.bar/login.php") window.location.href="login.php";

This doesn't need to be in a listener for the page load event.

EDIT :
Regarding your new descriptionn I would use (but would not recommend;)) something like :

if (location.pathname.indexOf("WebCode=LoginRequired")>0) {
    window.location.href="login.php";
}

Hope this will help.


问:
Autocomplete search is not displaying suggestions in asp.net mvc?
I want to display the autocomplete suggestion in the drop-drop list. But the suggestions are not displaying. I have tried with database and through list but result remains the same.

Here is the Code

Model contains ID and Name

HomeController.cs

```<code> public class HomeController : Controller
{
    // GET: Home
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public JsonResult Index(string Prefix)
    {
        //Note : you can bind same list from database
        List<City> ObjList = new List<City>()
        {

            new City {Id=1,Name="abc" },
            new City {Id=2,Name="def" },
            new City {Id=3,Name="ghi" },
            new City {Id=4,Name="jkl" },

    };
        //Searching records from list using LINQ query
        var CityName = (from N in ObjList
                        where N.Name.StartsWith(Prefix)
                        select new { N.Name });
        return Json(CityName, JsonRequestBehavior.AllowGet);
    }
</code>```

Index.cs

```<code><link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#CityName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Name, value: item.Name };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />

        <div class="form-group">

            <div class="col-md-12">
                @Html.EditorFor(model => model.CityName, new { htmlAttributes = new { @class = "form-control" } })

            </div>
        </div>

    </div>
}
</code>```

Please if anyone can guide me what am i lacking?
Thanks in advance.

答:
The CityName written in there is wrong because model do not contains CityName. just replace CityNameby Name. Then it will works finely.

```<code>$("#Name").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Home/Index",
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.Name, value: item.Name };
                    }))

                }
            })
        },
        messages: {
            noResults: "", results: ""
        }
    });
</code>```

and in view

```<code>@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
</code>```

Body:
I want to display the autocomplete suggestion in the drop-drop list. But the suggestions are not displaying. I have tried with database and through list but result remains the same.

Here is the Code

Model contains ID and Name

HomeController.cs

 public class HomeController : Controller
{
    // GET: Home
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public JsonResult Index(string Prefix)
    {
        //Note : you can bind same list from database
        List<City> ObjList = new List<City>()
        {

            new City {Id=1,Name="abc" },
            new City {Id=2,Name="def" },
            new City {Id=3,Name="ghi" },
            new City {Id=4,Name="jkl" },

    };
        //Searching records from list using LINQ query
        var CityName = (from N in ObjList
                        where N.Name.StartsWith(Prefix)
                        select new { N.Name });
        return Json(CityName, JsonRequestBehavior.AllowGet);
    }

Index.cs

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

                @Html.EditorFor(model => model.CityName, new { htmlAttributes = new { @class = "form-control" } })

}

Please if anyone can guide me what am i lacking?
Thanks in advance.

Body:
The CityName written in there is wrong because model do not contains CityName. just replace CityNameby Name. Then it will works finely.

$("#Name").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Home/Index",
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.Name, value: item.Name };
                    }))

                }
            })
        },
        messages: {
            noResults: "", results: ""
        }
    });

and in view

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })


问:
How to merge two forms into one?
I want to have these two buttons in one line, so Remove button is in the position in which it is and the Update mapping button is on the right.
So it would looks like this:

[![enter image description here][1]][1]

答:
Add style="display: inline-flex" at parent div.

UPDATE:

```<code><div class="collapse">
<th:block th:each="tmpl,iterStat : ${templates}">
    <input type="checkbox" th:id="'collapse-section' + ${iterStat.count}" aria-hidden="true"/>
    <label th:for="'collapse-section' + ${iterStat.count}" aria-hidden="true"><span ....></label>
    <div style="display: inline-flex">
        <form action="/.../delete" method="post" style="float: left; width 40%">
            <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                    class="secondary">Remove
            </button>
        </form>
        <div style="width: 20%"></div>
        <form action="/.../update" method="get" style="width: 40%">
            <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                    class="button primary">Update mapping
            </button>
        </form>
        <pre th:utext="${tmpl.response}"/>
    </div>
</th:block>
</code>```

Title: How to merge two forms into one?

Body:
Add style="display: inline-flex" at parent div.

UPDATE:

<div class="collapse">
<th:block th:each="tmpl,iterStat : ${templates}">
    <input type="checkbox" th:id="'collapse-section' + ${iterStat.count}" aria-hidden="true"/>
    <label th:for="'collapse-section' + ${iterStat.count}" aria-hidden="true"><span ....></label>
    <div style="display: inline-flex">
        <form action="/.../delete" method="post" style="float: left; width 40%">
            <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                    class="secondary">Remove
            </button>
        </form>
        <div style="width: 20%"></div>
        <form action="/.../update" method="get" style="width: 40%">
            <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                    class="button primary">Update mapping
            </button>
        </form>
        <pre th:utext="${tmpl.response}"/>
    </div>
</th:block>


问:
Adding additional boards in Azure Devops
In my team the list of boards, e.g. this page https://dev.azure.com/myorg/MentalHealth/_boards/directory, only contains one board, called 'MentalHealth Team boards' (N.B. I don't understand why that name is plural):

Other teams I work with have multiple boards listed. How do I add additional team boards?

答:
I don't understand why that name is plural

It's plural because you can have multiple boards here. For example, you can have boards for Epics and Issues:

Other teams I work with have multiple boards listed. How do I add additional team boards?

The All teams boards lists all boards of all teams, according to then img you provided, there is only one team MentalHealth Team in this project.

You can check Project Settings - Teams see if there is only one team in it.

In addition, you can see there are three team boards in my Boards since there are three teams in this project:


问:
Is there a way to hook Django's unittest into PyUnit in eclipse?
I've been working on a Django project for the past few weeks now, and it's been fairly smooth sailing. I use Django's unittest library to test everything, and the result show up in the console.

However, after doing some research, it looks like pydev provides facilities for PyUnit. I use Eclipse, and I thought I would just just be able to pipe the unit tests into PyUnit, but I haven't had any luck in either that or finding documentation to do so.

How do I have my unit tests run in the PyUnit view in eclipse?

Currently, I run all of my test within eclipse using the following:

```<code>manage.py test
</code>```

Thanks!

答:
I would recommend using Nose for your django tests.
Pydev allows you to choose your test runner, and it has support for nose.

I'll let stack explain why and how to integrate nose with eclipse for interactive debugging.

And i'll throw in the django-nose too.

Body:
I've been working on a Django project for the past few weeks now, and it's been fairly smooth sailing. I use Django's unittest library to test everything, and the result show up in the console.

However, after doing some research, it looks like pydev provides facilities for PyUnit. I use Eclipse, and I thought I would just just be able to pipe the unit tests into PyUnit, but I haven't had any luck in either that or finding documentation to do so.

How do I have my unit tests run in the PyUnit view in eclipse?

Currently, I run all of my test within eclipse using the following:

manage.py test

Thanks!


问:
How to redirect a user after a create method laravel6?
I made a register form in the front_page and I want to redirect the user after a successfull registration to /home page, but instead I get an array and the user is not redirected.

```<code>  {"email":"example@example.com","paypal_email":"example@example.com","updated_at":"2020-02-
  14
  08:16:32","created_at":"2020-02-14 08:16:32","id":1}
</code>```

My route:

```<code> Route::post('/', 'Auth\RegisterController@create')->name('auth.register');
</code>```

Register controller:

```<code>      public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

}

  public $redirectTo = '/home';
</code>```

答:
You should not call the create method directly, for a few reasons.

the request is not being validated.

if you want to trigger some events during registration that is not going to happen.

it's not going auto-login the user.

The create method is really for laravel trait RegistersUsers internal usage.
you can keep the controller like that, you only need to change your route to register.

Route::post('/', 'Auth\RegisterController@register')->name('auth.register');
```

By doing this the user should be created and redirected to home page.

And there is a reason why public $redirectTo = '/home'; this attribute exists, by  using the create method directly you are ignoring the attribute completely.

Body:
I made a register form in the front_page and I want to redirect the user after a successfull registration to /home page, but instead I get an array and the user is not redirected.

  {"email":"example@example.com","paypal_email":"example@example.com","updated_at":"2020-02-
  14
  08:16:32","created_at":"2020-02-14 08:16:32","id":1}

My route:

 Route::post('/', 'Auth\RegisterController@create')->name('auth.register');

Register controller:

      public function create(Request $request)
{
    return User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

}

  public $redirectTo = '/home';

Body:
You should not call the create method directly, for a few reasons.

the request is not being validated.

if you want to trigger some events during registration that is not going to happen.

it's not going auto-login the user.

The create method is really for laravel trait RegistersUsers internal usage.
you can keep the controller like that, you only need to change your route to register.

Route::post('/', 'Auth\RegisterController@register')->name('auth.register');

By doing this the user should be created and redirected to home page.

And there is a reason why public $redirectTo = '/home'; this attribute exists, by  using the create method directly you are ignoring the attribute completely.


问:
Meaning of inter_op_parallelism_threads and intra_op_parallelism_threads
Can somebody please explain the following TensorFlow terms

inter_op_parallelism_threads

intra_op_parallelism_threads

or, please, provide links to the right source of explanation.

I have conducted a few tests by changing the parameters, but the results have not been consistent to arrive at a conclusion.

答:
Tensorflow 2.0 Compatible Answer: If we want to execute in Graph Mode of Tensorflow Version 2.0, the function in which we can configure inter_op_parallelism_threads and intra_op_parallelism_threads is

tf.compat.v1.ConfigProto.


问:
Running CPython functions from C#
I'm working on a project where I need to be able to run a python function that depends on SciPy/NumPy.  Due to this being an add-on to a project already in progress, using IronPython would not be an option.

Additional info:

Python.NET seemed to be a good fit, but I was unable to get the return value from RunString() (it would only return NULL).

Passing arguments and catching the return value (a tuple) is necessary.

The function is in a statistical package that was created by a support group for the team, so modification of that would also not be possible.

I'm at quite a loss for what to do. Any hints in the right direction are appreciated. Thanks for any help you can give!

I understand that this may be quite vague, but I cannot give explicit details to the project. If any clarification is needed please let me know and I'll do my best!

答: IronPython using DLR might be the way to go.  Mind you it won't be the fastest way, but it seems like something worth pursuing if you're going to do this a lot.  Another useful link</p>

Title: Running CPython functions from C#


问:
How to add a download hyperlink for downloading attachments from website in odoo
I want to add a hyperlink in the website module in odoo using which I can download the attachments which consists of information of the product which was created.Please help with with this problem .
Thank you</p>

答:
If this is for a form you could do this entirely in the view. First add a record entry somewhere in the xml file:

```<code><record id="module_name.http_link" model="ir.actions.act_url">
  <field name="name">Button Name</field>
  <field name="type">ir.actions.act_url</field>
  <field name="target">new</field>
  <field name="url">https://your-http-link</field>
</record>
</code>```

And then in the form:

```<code><button type="action" name="%(http_link)d" string="Name" class="oe_highlight"/>
</code>```

Body:
If this is for a form you could do this entirely in the view. First add a record entry somewhere in the xml file:

<record id="module_name.http_link" model="ir.actions.act_url">
  <field name="name">Button Name</field>
  <field name="type">ir.actions.act_url</field>
  <field name="target">new</field>
  <field name="url">https://your-http-link</field>
</record>

And then in the form:

<button type="action" name="%(http_link)d" string="Name" class="oe_highlight"/>


问:
C# Add extra property/info to a Image
I want to add a extra property or info to a image.
I tried using a new class that gets the image propertys and i just add one, but i have no idea how to do this.

Also i cant use the property "Tag" thats already in use, and cant be overwritten

```<code>public partial class myImage : System.Windows.Controls.Image
{
        //?
}
</code>```

答:
Gets or sets a value that represents the author of an image.

```<code>public System.Collections.ObjectModel.ReadOnlyCollection<string> Author { get; set; }
</code>```

The following code example shows how to write metadata to a bitmap image by using friendly properties of the BitmapMetadata class.

```<code>FileStream stream3 = new FileStream( "image2.tif", FileMode.Create );
BitmapMetadata myBitmapMetadata = new BitmapMetadata( "tiff" );
TiffBitmapEncoder encoder3 = new TiffBitmapEncoder();
myBitmapMetadata.ApplicationName = "Microsoft Digital Image Suite 10";
myBitmapMetadata.Author = new ReadOnlyCollection<string>(
    new List<string>() { "Mehdi Daustany" } );
myBitmapMetadata.CameraManufacturer = "Tailspin Toys";
myBitmapMetadata.CameraModel = "TT23";
myBitmapMetadata.Comment = "Nice Picture";
myBitmapMetadata.Copyright = "2010";
myBitmapMetadata.DateTaken = "5/23/2010";
myBitmapMetadata.Keywords = new ReadOnlyCollection<string>(
    new List<string>() { "Mehdi", "Daustany" } );
myBitmapMetadata.Rating = 5;
myBitmapMetadata.Subject = "Mehdi";
myBitmapMetadata.Title = "Mehdi's photo";

// Create a new frame that is identical to the one
// from the original image, except for the new metadata.
encoder3.Frames.Add(
    BitmapFrame.Create(
    decoder2.Frames[0],
    decoder2.Frames[0].Thumbnail,
    myBitmapMetadata,
    decoder2.Frames[0].ColorContexts ) );

encoder3.Save( stream3 );
stream3.Close();
</code>```

Title: C# Add extra property/info to a Image

Body:
I want to add a extra property or info to a image.
I tried using a new class that gets the image propertys and i just add one, but i have no idea how to do this.

Also i cant use the property "Tag" thats already in use, and cant be overwritten

public partial class myImage : System.Windows.Controls.Image
{
        //?
}

Body:
Gets or sets a value that represents the author of an image.

public System.Collections.ObjectModel.ReadOnlyCollection<string> Author { get; set; }

The following code example shows how to write metadata to a bitmap image by using friendly properties of the BitmapMetadata class.

FileStream stream3 = new FileStream( "image2.tif", FileMode.Create );
BitmapMetadata myBitmapMetadata = new BitmapMetadata( "tiff" );
TiffBitmapEncoder encoder3 = new TiffBitmapEncoder();
myBitmapMetadata.ApplicationName = "Microsoft Digital Image Suite 10";
myBitmapMetadata.Author = new ReadOnlyCollection<string>(
    new List<string>() { "Mehdi Daustany" } );
myBitmapMetadata.CameraManufacturer = "Tailspin Toys";
myBitmapMetadata.CameraModel = "TT23";
myBitmapMetadata.Comment = "Nice Picture";
myBitmapMetadata.Copyright = "2010";
myBitmapMetadata.DateTaken = "5/23/2010";
myBitmapMetadata.Keywords = new ReadOnlyCollection<string>(
    new List<string>() { "Mehdi", "Daustany" } );
myBitmapMetadata.Rating = 5;
myBitmapMetadata.Subject = "Mehdi";
myBitmapMetadata.Title = "Mehdi's photo";

// Create a new frame that is identical to the one
// from the original image, except for the new metadata.
encoder3.Frames.Add(
    BitmapFrame.Create(
    decoder2.Frames[0],
    decoder2.Frames[0].Thumbnail,
    myBitmapMetadata,
    decoder2.Frames[0].ColorContexts ) );

encoder3.Save( stream3 );
stream3.Close();