问:
Fastest way to fill or read from a QTableWidget in PyQt5
I have a QTableWidget in PyQt5 which I fill from a python dictionary of numpy array or a pandas DataFrame.

Question

I want to fill or read from QTableWidget in a 'vectorized' way as per operating over array rather than row,col values.  I have seen other examples using QTableView in this post How can I retrieve data from a QTableWidget to Dataframe? but this still operates over individuals values rather than arrays or lists. Is this possible?

Generally I do this when I operate over row, col values:

```<code># To Writte
TableWidget.setItem(row, col, tableItem)

# To Read
TableWidget.item(i, j).data()
</code>```

I would like to do something like this:

```<code># To Writte
TableWidget.setColumn(col, array_items)

# To Read
TableWidget.getColumn(col).data()
</code>```

I would prefer to keep using QTableWidget, but I am open to other options like QTableView.
I appreciate any help, Marcelo.

答:
It's possible to do that using TableView and re-implemented QAbstractTableModel. Instead of TableWidget.setColumn(col, array_items), You will call TableWidget.model().setColumn(col, array_items). In principle to have it working with TableWidget, You have to re-implement QTableWidget class, but I found that unnecessary.

In my example I used pandas DataFrame as a data holder. You can set and get data using column name.

Here is fully working example:

```<code>import sys
import typing

import pandas as pd
from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QWidget, QGridLayout, QPushButton

class TableModel(QAbstractTableModel):

    def __init__(self, table_data, parent=None):
        super().__init__(parent)
        self.table_data = table_data

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return self.table_data.shape[0]

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return self.table_data.shape[1]

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if role == Qt.DisplayRole:
            return str(self.table_data.loc[index.row()][index.column()])

    def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return str(self.table_data.columns[section])

    def setColumn(self, col, array_items):
        """Set column data"""
        self.table_data[col] = array_items
        # Notify table, that data has been changed
        self.dataChanged.emit(QModelIndex(), QModelIndex())

    def getColumn(self, col):
        """Get column data"""
        return self.table_data[col]

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QMainWindow()

    widget = QWidget()

    layout = QGridLayout()
    widget.setLayout(layout)
    table_data = pd.DataFrame(data={'col1': [1, 2, 3, 4, 5, 6, 7, 8], 'col2': [1, 2, 3, 4, 5, 6, 7, 8]})
    table = QTableView()
    table.setModel(TableModel(table_data=table_data))
    layout.addWidget(table)

    button = QPushButton("Set col1")
    button.clicked.connect(lambda: table.model().setColumn("col1", [8, 7, 6, 5, 4, 3, 2, 1]))

    button_2 = QPushButton("Read col1")
    button_2.clicked.connect(lambda: print(table.model().getColumn("col1")))

    layout.addWidget(button)
    layout.addWidget(button_2)
    win.setCentralWidget(widget)

    win.show()
    app.exec()
</code>```

Body:
I have a QTableWidget in PyQt5 which I fill from a python dictionary of numpy array or a pandas DataFrame.

Question

I want to fill or read from QTableWidget in a 'vectorized' way as per operating over array rather than row,col values.  I have seen other examples using QTableView in this post How can I retrieve data from a QTableWidget to Dataframe? but this still operates over individuals values rather than arrays or lists. Is this possible?

Generally I do this when I operate over row, col values:

# To Writte
TableWidget.setItem(row, col, tableItem)

# To Read
TableWidget.item(i, j).data()

I would like to do something like this:

# To Writte
TableWidget.setColumn(col, array_items)

# To Read
TableWidget.getColumn(col).data()

I would prefer to keep using QTableWidget, but I am open to other options like QTableView.
I appreciate any help, Marcelo.

Body:
It's possible to do that using TableView and re-implemented QAbstractTableModel. Instead of TableWidget.setColumn(col, array_items), You will call TableWidget.model().setColumn(col, array_items). In principle to have it working with TableWidget, You have to re-implement QTableWidget class, but I found that unnecessary.

In my example I used pandas DataFrame as a data holder. You can set and get data using column name.

Here is fully working example:

import sys
import typing

import pandas as pd
from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QWidget, QGridLayout, QPushButton

class TableModel(QAbstractTableModel):

    def __init__(self, table_data, parent=None):
        super().__init__(parent)
        self.table_data = table_data

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return self.table_data.shape[0]

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return self.table_data.shape[1]

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if role == Qt.DisplayRole:
            return str(self.table_data.loc[index.row()][index.column()])

    def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return str(self.table_data.columns[section])

    def setColumn(self, col, array_items):
        """Set column data"""
        self.table_data[col] = array_items
        # Notify table, that data has been changed
        self.dataChanged.emit(QModelIndex(), QModelIndex())

    def getColumn(self, col):
        """Get column data"""
        return self.table_data[col]

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = QMainWindow()

    widget = QWidget()

    layout = QGridLayout()
    widget.setLayout(layout)
    table_data = pd.DataFrame(data={'col1': [1, 2, 3, 4, 5, 6, 7, 8], 'col2': [1, 2, 3, 4, 5, 6, 7, 8]})
    table = QTableView()
    table.setModel(TableModel(table_data=table_data))
    layout.addWidget(table)

    button = QPushButton("Set col1")
    button.clicked.connect(lambda: table.model().setColumn("col1", [8, 7, 6, 5, 4, 3, 2, 1]))

    button_2 = QPushButton("Read col1")
    button_2.clicked.connect(lambda: print(table.model().getColumn("col1")))

    layout.addWidget(button)
    layout.addWidget(button_2)
    win.setCentralWidget(widget)

    win.show()
    app.exec()


来源: stackexchange

问:
Is it necessary to use underscore (_) variable inside functions in Dart?
The variable/function name starts with underscore "_" means that it is a private variable/function in Dart language. It is well-known.

What if the underscore variable is used inside a function?

Is it necessary to use declare an underscored variable in a function(not in a class) to denote that the variable is only used in the function? or as it is self-evident that the declared variable can only be used in the function so that using underscore prefix is just a redundant thing? (or for the naming convention?) (when the function does not have any inner-function)

With underscore:

```<code>void sample() {
 var _something = getSomething();
 doSomethingWith(_something);
 //use _something
}
</code>```

Without underscore:

```<code>void sample() {
 var something = getSomething();
 doSomethingWith(something);
 //use something
}
</code>```

Plus, is there any performance-related difference between them?

答:
Dai is right about almost everything but I want to correct him. Primitives (like int, bool, and num) are passed by value. Objects are passed by reference. So doSomethingWith will have reference to _something if _something is not a primitive
But it doesn't change the answer. You don't need to underscore variables in methods.

ContentLicense: CC BY-SA 4.0

Body:
The variable/function name starts with underscore "_" means that it is a private variable/function in Dart language. It is well-known.

What if the underscore variable is used inside a function?

Is it necessary to use declare an underscored variable in a function(not in a class) to denote that the variable is only used in the function? or as it is self-evident that the declared variable can only be used in the function so that using underscore prefix is just a redundant thing? (or for the naming convention?) (when the function does not have any inner-function)

With underscore:

void sample() {
 var _something = getSomething();
 doSomethingWith(_something);
 //use _something
}

Without underscore:

void sample() {
 var something = getSomething();
 doSomethingWith(something);
 //use something
}

Plus, is there any performance-related difference between them?


问:
Google play console message: Newly supported devices is zero (0)
I want to release a new update for my app but in google play console it display 0 in Newly supported device, I don't use any feature in my app! is it important at all?

this is google play console:

(devices no longer support is for increasing minimum sdk)

this is my manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.kolbe.fale_ghahve">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/fortuneteller"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/fortuneteller_round"
    android:networkSecurityConfig="@xml/network_security_config"
    android:supportsRtl="true"
    android:largeHeap="true"
    android:theme="@style/Theme.MyApplication">
    <activity
        android:name=".SplashScreenActivity"
        android:theme="@style/SplashTheme"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MainActivity" android:screenOrientation="portrait"/>
    <activity android:name=".settingActivity" />
    <activity android:name=".TarootActivity" />
    <activity android:name=".sheikh.showJadvalAuto" android:screenOrientation="portrait" />

    <service android:name=".Utils.BackgroundSoundService" />
    <!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-7990391538461789~6976996140"/>
</application>
</manifest>
</code>```

and this is my dependencies in build.gradle:

答: I got it, it is newly supported device, not supported device it just says no new device is supported with last update but old ones are still in support</p>

Body:
I want to release a new update for my app but in google play console it display 0 in Newly supported device, I don't use any feature in my app! is it important at all?

this is google play console:

(devices no longer support is for increasing minimum sdk)

this is my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.kolbe.fale_ghahve">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/fortuneteller"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/fortuneteller_round"
    android:networkSecurityConfig="@xml/network_security_config"
    android:supportsRtl="true"
    android:largeHeap="true"
    android:theme="@style/Theme.MyApplication">
    <activity
        android:name=".SplashScreenActivity"
        android:theme="@style/SplashTheme"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MainActivity" android:screenOrientation="portrait"/>
    <activity android:name=".settingActivity" />
    <activity android:name=".TarootActivity" />
    <activity android:name=".sheikh.showJadvalAuto" android:screenOrientation="portrait" />

    <service android:name=".Utils.BackgroundSoundService" />

    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-7990391538461789~6976996140"/>
</application>
</manifest>

and this is my dependencies in build.gradle:


问:
random image on load
I have found several scripts but i don't get them to work:
What am i doing wrong;

I want to change the color and some images on my page, so the second time you visite the page you may get another color.

I get the font color to change, but having problems with my image.

the js:

```<code>$(document).ready(function(){
  var colors = ["#D4FF00","#E18000","#ED4498","#0080C0"];
  var Rlogo= ['BIMP_groen.jpg','BIMP_oranje.jpg','BIMP_roze.jpg','BIMP_blauw.jpg'];
  var rand = Math.floor(Math.random()*colors.length);
  $('a').css("color", colors[rand]);
  $('h2').css("color", colors[rand]);
  $('<img src="images/logo/' + Rlogo[rand] + '">').appendTo('#logo');
  });
</code>```

in my html i have;

```<code><img src="images/logo/BIMP_oranje.jpg" id="logo" align="right" alt='align="right"'>
</code>```

the image doesn;t change on refresh.

please help

答:
You need to replace the image in the logos parent element:</p>

```<code><div id="logoParent">
<img src="images/logo/BIMP_oranje.jpg" id="logo" align="right" alt='align="right"'/>
</div>
<script type="text/javascript">
$('#logoParent').html('<img src="images/logo/' + Rlogo[rand] + '"/>');
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Title: random image on load

Body:
I have found several scripts but i don't get them to work:
What am i doing wrong;

I want to change the color and some images on my page, so the second time you visite the page you may get another color.

I get the font color to change, but having problems with my image.

the js:

$(document).ready(function(){
  var colors = ["#D4FF00","#E18000","#ED4498","#0080C0"];
  var Rlogo= ['BIMP_groen.jpg','BIMP_oranje.jpg','BIMP_roze.jpg','BIMP_blauw.jpg'];
  var rand = Math.floor(Math.random()*colors.length);
  $('a').css("color", colors[rand]);
  $('h2').css("color", colors[rand]);
  $('').appendTo('#logo');
  });

in my html i have;

the image doesn;t change on refresh.

please help

Body:
You need to replace the image in the logos parent element:

<div id="logoParent">
<img src="images/logo/BIMP_oranje.jpg" id="logo" align="right" alt='align="right"'/>
</div>
<script type="text/javascript">
$('#logoParent').html('<img src="images/logo/' + Rlogo[rand] + '"/>');
</script>


问:
Azure pipelines failing on specific deploy jobs
On only two of my pipeline jobs I keep getting this error:

```<code>##[error]No hosted parallelism has been purchased or granted. To request a free parallelism grant, please fill out the following form https://aka.ms/azpipelines-parallelism-request
</code>```

This doesnt happen on any of the other jobs in the pipeline.

This only started happening on 9th of February.

I've seen in the past that public projects were stopped from using parallelizm in pipelines (which I dont even think I'm using). But my project has been using Azure Pipelines before this was implemented, and these changes were not supposed to affect existing projects.

Is there a reason this has started happening recently? I cannot re-start the jobs either, the same error occurs.

答:
Azure pipelines failing on specific deploy jobs

It seems that the hosted pipeline parallelism disabled (earlier working) after 8th Feb for some customers.

To resolve this issue, I recommend you need to create a technical support ticket from Azure Portal if you have Azure support plans to ask product team to resolve this in banckend.

Body:
On only two of my pipeline jobs I keep getting this error:

##[error]No hosted parallelism has been purchased or granted. To request a free parallelism grant, please fill out the following form https://aka.ms/azpipelines-parallelism-request

This doesnt happen on any of the other jobs in the pipeline.

This only started happening on 9th of February.

I've seen in the past that public projects were stopped from using parallelizm in pipelines (which I dont even think I'm using). But my project has been using Azure Pipelines before this was implemented, and these changes were not supposed to affect existing projects.

Is there a reason this has started happening recently? I cannot re-start the jobs either, the same error occurs.


问:
Jest:- TypeError: Cannot read properties of undefined (reading 'params'). Error coming in jest
I have below component in react. I put in short only

```<code>export interface EditCertificateProps {
    id:string;
}

export function EditCertificate(props: any) {
 injectStyle();

 const {id} = props.match.params;
 const history = useHistory();
}
</code>```

When I am doing jest testing it is throwing error.

```<code>const id = '123';
describe('EditCertificate', () => {
    const params = {
        id: '123',
    };
    it('should render successfully', () => {
        const { baseElement } = render(<EditCertificate id={id} />);
        expect(baseElement).toBeTruthy();
    });
});
</code>```

it is throwing error

from another component this page gets called like below.

```<code>  <SecureRoute path="/:id/edit" component={EditCertificate} />
</code>```

I changed my testcase like below still error.

```<code>describe('EditCertificate', () => {
    const props = {
        match: {
            params: 123,
        },
    };
    it('should render successfully', () => {
        const { baseElement } = render(<EditCertificate {...props.match.params} />);
        expect(baseElement).toBeTruthy();
    });
});
</code>```

what wrong I am doing?

答:
The EditCertificate component is expecting a match prop with a params property.

```<code>export function EditCertificate(props: any) {
  injectStyle();

  const {id} = props.match.params;
  const history = useHistory();

  ...
}
</code>```

This match prop needs to be provided in the unit test. You are creating a props object so you can just spread that into EditCertificate. Spread the entire props object, not props.match.params, the latter only spreads the individual params.

```<code>describe('EditCertificate', () => {
  const props = {
    match: {
      params: {
        id: 123, // <-- props.match.params.id
      },
    },
  };

  it('should render successfully', () => {
    const { baseElement } = render(<EditCertificate {...props} />);
    expect(baseElement).toBeTruthy();
  });
});
</code>```

The next issue will be a missing routing context for the useHistory hook. You can provide a wrapper for the render util, or simply wrap EditCertificate directly.

```<code>const RouterWrapper = ({ children }) => (
  <MemoryRouter>{children}</MemoryRouter> // *
);

...

const { baseElement } = render(
  <EditCertificate {...props} />,
  {
    wrapper: RouterWrapper
  },
);
</code>```

or

```<code>const { baseElement } = render(
  <MemoryRouter>
    <EditCertificate {...props} />
  </MemoryRouter>
);
</code>```

* MemoryRouter used for unit testing since there is no DOM

Body:
I have below component in react. I put in short only

export interface EditCertificateProps {
    id:string;
}

export function EditCertificate(props: any) {
 injectStyle();

 const {id} = props.match.params;
 const history = useHistory();
}

When I am doing jest testing it is throwing error.

const id = '123';
describe('EditCertificate', () => {
    const params = {
        id: '123',
    };
    it('should render successfully', () => {
        const { baseElement } = render(<EditCertificate id={id} />);
        expect(baseElement).toBeTruthy();
    });
});

it is throwing error

from another component this page gets called like below.

  <SecureRoute path="/:id/edit" component={EditCertificate} />

I changed my testcase like below still error.

describe('EditCertificate', () => {
    const props = {
        match: {
            params: 123,
        },
    };
    it('should render successfully', () => {
        const { baseElement } = render(<EditCertificate {...props.match.params} />);
        expect(baseElement).toBeTruthy();
    });
});

what wrong I am doing?

Body:
The EditCertificate component is expecting a match prop with a params property.

export function EditCertificate(props: any) {
  injectStyle();

  const {id} = props.match.params;
  const history = useHistory();

  ...
}

This match prop needs to be provided in the unit test. You are creating a props object so you can just spread that into EditCertificate. Spread the entire props object, not props.match.params, the latter only spreads the individual params.

describe('EditCertificate', () => {
  const props = {
    match: {
      params: {
        id: 123, // <-- props.match.params.id
      },
    },
  };

  it('should render successfully', () => {
    const { baseElement } = render(<EditCertificate {...props} />);
    expect(baseElement).toBeTruthy();
  });
});

The next issue will be a missing routing context for the useHistory hook. You can provide a wrapper for the render util, or simply wrap EditCertificate directly.

const RouterWrapper = ({ children }) => (
  <MemoryRouter>{children}</MemoryRouter> // *
);

...

const { baseElement } = render(
  <EditCertificate {...props} />,
  {
    wrapper: RouterWrapper
  },
);

or

const { baseElement } = render(
  <MemoryRouter>
    <EditCertificate {...props} />
  </MemoryRouter>
);

* MemoryRouter used for unit testing since there is no DOM


问:
Why does this code throw a (ambiguous) internal compiler error?
This function produces the following error (compiled by hardhat)

Solidity 0.8.7

```<code>contract TestContract {
  function slice(string calldata source, uint from, uint to) public pure returns(string memory) {
    bytes calldata b = (bytes(source));
    uint len = b.length;
    require(to < len && to>=from, "indexes out of bounds");
    string memory retval = string(b[from:to]);
    return retval;
}
</code>```

}

The error I get is Compiling 1 file with 0.8.7 InternalCompilerError: Internal compiler error (/Users/distiller/project/libsolidity/codegen/CompilerUtils.cpp:1116) Error HH600: Compilation failed

答: I'm not sure about how you convert bytes to string, but the error might come from string(b[from:to]);. You can reference the byteToString function provided here https://ethereum.stackexchange.com/questions/29295/how-to-convert-a-bytes-to-string-in-solidity.

Body:
This function produces the following error (compiled by hardhat)

Solidity 0.8.7

contract TestContract {
  function slice(string calldata source, uint from, uint to) public pure returns(string memory) {
    bytes calldata b = (bytes(source));
    uint len = b.length;
    require(to < len && to>=from, "indexes out of bounds");
    string memory retval = string(b[from:to]);
    return retval;
}

}

The error I get is Compiling 1 file with 0.8.7 InternalCompilerError: Internal compiler error (/Users/distiller/project/libsolidity/codegen/CompilerUtils.cpp:1116) Error HH600: Compilation failed


问:
Syndication Feed View RSS to File
I'm using django as my web frontend for my podcast. I use a CDN for hosting all my media, and lately I have wanted that same CDN to host my RSS Feed, not directly django.

The current setup has some basic well known primitives:

```<code>    path('podcast.xml', SubscribeFeed(), name='episode_feed'),
</code>```

Some additional context; SubscribeFeed is a Syndication Feed (https://github.com/django/django/blob/main/django/contrib/syndication/views.py#L27) that is based off of the https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/#custom-feed-generators

And it looks somewhat like:

```<code>class iTunesFeed(Rss201rev2Feed):
    content_type = 'application/xml; charset=utf-8'

    def root_attributes(self):
        attrs = super().root_attributes()
        attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
        return attrs
    < ... Ripped right from the custom feed generators with a ton of extra elements for the specific podcast category and such ... >

 class SubscribeFeed(Feed):
    title = "My Cool Podcast"
    description = About.objects.first().about
    author_email = "podcast@gmail.com"
    author_name = "John Doe"
    feed_type = iTunesFeed

    def item_pubdate(self, item):
        return item.pub_date
    < ... More stuff that isn't relevant ... >
</code>```

Just to be clear this view works perfectly with Django serving the podcast RSS. It works in all major platforms and is very nice.

My problem/question is that: I want to generate/render this view to a text file, the purpose being; I host media on a CDN, I would also benefit myself to put this RSS Feed on a separate feeds.mypodcast.com CDN. In this way, the django app could go down but the feed and media would still be accessible via CDN. The django app is only in the critical path for; episode descriptions, contact forms, web ui episode browsing, etc.

I am already running celery to release the episodes at a given interval so my plan is the following:

Create an async function run after a model save() function that

Generates a new feed to a file or string

Compares what's on the CDN

Replaces the CDN RSS feed file and invalidates CDN cache.

Step 2 and 3 are very simple but I'm struggling with generating to a file.

Things I have tried:

"Mocking" requests and running get_feed podcast_feed.get_feed(podcast_feed.items(), <mocked request object>)
** This certainly "works" but calling my own REST resources feels bad and is not great.

Creating a "hidden" URL dispatcher. Then on a celery beat schedule, I hit this URL from my celery task. Generate the view via requests, compare and redistribute on CDN.
** This also "works" but similarly feels bad.

Writing my own get_feed() type of function.
** This didn't really work. Reading the source I found it rather dependent on a valid request and I didn't think I was architecturally doing it in the right place. (creating my own feedgenerator)

render_to_string but for Syndication Feeds. ** This stopped almost immediately. Worked well on a normal view but couldn't figure it out on feeds.

I've been banging my head on this for quite a while. The "hidden" dispatch feels like the safest and most efficacious hack, but I'd prefer to do it the right way.

What my question is really looking for is architectural guidance. What is the right way to do this? I was hoping to find something obvious like render_to_string but for syndication feeds. Implementing my own feedgenerator was not working well.

What is the best path forward to solve the use case of simply; Rendering a Syndication Feed View to a text file?

Thanks.

答:
I am selecting my answer because I thought a bit more about the problem set. Django's MVT/MVC pattern is really nice, but I think I was asking it to do something it ought not do.

Making a View from a Template ala Django Syndication Feed was great if I wanted to serve the RSS feed from the Django app itself. But as stated in the question I wanted to write this RSS feed off to some remote CDN.

I accomplished this by writing my own wrapper around rfeed (note: the one in pypi is a older fork...). Which pulls in all my episodes and podcast metadata models, feeds them into items, then to a feed.

I then wrote a simple async task on model save (or scheduled episode release) that simply generates the rfeed RSS feed, creates an S3 object, diffs what's in S3, then conditionally pushes to S3 and invalidates the cloudfront CDN.

I quite like this approach because now my django app should something bad happen go offline. All media and RSS is now in the CDN, the site is just used for show notes, contact forms, about us, simple things. The critical infra is now the cloud providers problem.

Title: Syndication Feed View RSS to File

Body:
I'm using django as my web frontend for my podcast. I use a CDN for hosting all my media, and lately I have wanted that same CDN to host my RSS Feed, not directly django.

The current setup has some basic well known primitives:

    path('podcast.xml', SubscribeFeed(), name='episode_feed'),

Some additional context; SubscribeFeed is a Syndication Feed (https://github.com/django/django/blob/main/django/contrib/syndication/views.py#L27) that is based off of the https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/#custom-feed-generators

And it looks somewhat like:

class iTunesFeed(Rss201rev2Feed):
    content_type = 'application/xml; charset=utf-8'

    def root_attributes(self):
        attrs = super().root_attributes()
        attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
        return attrs
    < ... Ripped right from the custom feed generators with a ton of extra elements for the specific podcast category and such ... >

 class SubscribeFeed(Feed):
    title = "My Cool Podcast"
    description = About.objects.first().about
    author_email = "podcast@gmail.com"
    author_name = "John Doe"
    feed_type = iTunesFeed

    def item_pubdate(self, item):
        return item.pub_date
    < ... More stuff that isn't relevant ... >

Just to be clear this view works perfectly with Django serving the podcast RSS. It works in all major platforms and is very nice.

My problem/question is that: I want to generate/render this view to a text file, the purpose being; I host media on a CDN, I would also benefit myself to put this RSS Feed on a separate feeds.mypodcast.com CDN. In this way, the django app could go down but the feed and media would still be accessible via CDN. The django app is only in the critical path for; episode descriptions, contact forms, web ui episode browsing, etc.

I am already running celery to release the episodes at a given interval so my plan is the following:

Create an async function run after a model save() function that

Generates a new feed to a file or string

Compares what's on the CDN

Replaces the CDN RSS feed file and invalidates CDN cache.

Step 2 and 3 are very simple but I'm struggling with generating to a file.

Things I have tried:

"Mocking" requests and running get_feed podcast_feed.get_feed(podcast_feed.items(), <mocked request object>)
** This certainly "works" but calling my own REST resources feels bad and is not great.

Creating a "hidden" URL dispatcher. Then on a celery beat schedule, I hit this URL from my celery task. Generate the view via requests, compare and redistribute on CDN.
** This also "works" but similarly feels bad.

Writing my own get_feed() type of function.
** This didn't really work. Reading the source I found it rather dependent on a valid request and I didn't think I was architecturally doing it in the right place. (creating my own feedgenerator)

render_to_string but for Syndication Feeds. ** This stopped almost immediately. Worked well on a normal view but couldn't figure it out on feeds.

I've been banging my head on this for quite a while. The "hidden" dispatch feels like the safest and most efficacious hack, but I'd prefer to do it the right way.

What my question is really looking for is architectural guidance. What is the right way to do this? I was hoping to find something obvious like render_to_string but for syndication feeds. Implementing my own feedgenerator was not working well.

What is the best path forward to solve the use case of simply; Rendering a Syndication Feed View to a text file?

Thanks.


问:
JS Return HTML Title as H1 Headline
first of all: I‘m not a coder!

I want to inject a dynamic h1 based on page title on a webpage.

Example: <title>Garden</title>

Now I need this as H1 class -  I want to include this H1 after a given div class

It is may totally simple and I already read some stuff but i don‘t get it…

答:
Fairly trivial

window.addEventListener('DOMContentLoaded', function() {
  const h1 = document.createElement('h1')
  h1.innerHTML = document.title;
  document.querySelector(".teaser").insertAdjacentElement("afterend", h1)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Garden</title>
</head>

<body>
  <div class="teaser">Teaser</div>
</body>

</html></code>```

Title: JS Return HTML Title as H1 Headline

Body:
Fairly trivial

window.addEventListener('DOMContentLoaded', function() {
  const h1 = document.createElement('h1')
  h1.innerHTML = document.title;
  document.querySelector(".teaser").insertAdjacentElement("afterend", h1)
})

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Garden</title>
</head>

<body>
  <div class="teaser">Teaser</div>
</body>

</html>


问:
measuring a view before rendering it
I need to find out how big a view will be after attaching it to its parent.

I have overridden this method:

```<code>onMeasure(int, int);
</code>```

but it looks like this method is invoked only when I actually add my custom view to it's container using:

```<code>addView(myView);
</code>```

Do you think there is a way to get this information before rendering the view itself? Basically I need to know the actuall size before attaching it and not attach the view at all if it would take more certain amount of space.

anybody?

答: I'm having the same problem. I guess the only way is to render it first, then remove it after if it meets the size condition. Seems a bit of an odd way, but Android only seems to know the dimensions after drawing.

ContentLicense: CC BY-SA 2.5

Title: measuring a view before rendering it

Body:
I need to find out how big a view will be after attaching it to its parent.

I have overridden this method:

onMeasure(int, int);

but it looks like this method is invoked only when I actually add my custom view to it's container using:

addView(myView);

Do you think there is a way to get this information before rendering the view itself? Basically I need to know the actuall size before attaching it and not attach the view at all if it would take more certain amount of space.

anybody?


问:
Swift async/await what it the replacement of DispatchQueue.main.async
How I can return to main thread when using async/await concurrency mechanism in new Swift 5.5? Should I just mark function, class with @MainActor.
Can I still use DispatchQueue.main.async? Will it be correct? As new mechanism doesn't use GCD and there is no mapping between async tasks and thread like before?

For example I am using SwiftUI List with refreshable

```<code>List { }
.refreshable {
    viewModel.fetchData()
}
</code>```

Is this ok

```<code>List { }
.refreshable {
    DispatchQueue.main.async {
      viewModel.fetchData()
    }
}
</code>```

Or I need to add @MainActor on ViewModel class?
I doesn't use async/await in project so using MainActor just for this single refreshable seems redundant, I also doesn't know how adding such attribute influance remaining methods and properties of ViewModel class, they now use Combine.

But on the other hand Xcode displays

runtime: SwiftUI: Publishing changes from background threads is not
allowed; make sure to publish values from the main thread (via
operators like receive(on:)) on model updates.

Moreover after adding @MainActor to ViewModel I am getting multiple warnings like this

Property 'title' isolated to global actor 'MainActor' can not satisfy
corresponding requirement from protocol
'OnlineBankingListViewModelProtocol'

答: In a lot of cases, the new async model will work out what thread is best suited to execute a task, if your task has access to Guide objects, the compiler/runtime will choose to run the entire task in the main thread, if you have other things you want to run in the main thread, you can use @ MainActor, but the more stuff you force in the main thread, the more work you will put on that thread and the less work will be given to other threads, and so less chance for your work to be spread across multiple cores. If you really push it you can get a task to run in the background thread that access Guide stuff, and you will find execution will jump to the main thread to execute the GUI call. If there are a set of calls you want to run in the main thread with some gui code you code just wrap them in a task, and the the runtime system sort it our for you.</p>

Body:
How I can return to main thread when using async/await concurrency mechanism in new Swift 5.5? Should I just mark function, class with @MainActor.
Can I still use DispatchQueue.main.async? Will it be correct? As new mechanism doesn't use GCD and there is no mapping between async tasks and thread like before?

For example I am using SwiftUI List with refreshable

List { }
.refreshable {
    viewModel.fetchData()
}

Is this ok

List { }
.refreshable {
    DispatchQueue.main.async {
      viewModel.fetchData()
    }
}

Or I need to add @MainActor on ViewModel class?
I doesn't use async/await in project so using MainActor just for this single refreshable seems redundant, I also doesn't know how adding such attribute influance remaining methods and properties of ViewModel class, they now use Combine.

But on the other hand Xcode displays

runtime: SwiftUI: Publishing changes from background threads is not
allowed; make sure to publish values from the main thread (via
operators like receive(on:)) on model updates.

Moreover after adding @MainActor to ViewModel I am getting multiple warnings like this

Property 'title' isolated to global actor 'MainActor' can not satisfy
corresponding requirement from protocol
'OnlineBankingListViewModelProtocol'


问:
I can't see buttons in MaterialButtonToggleGroup
I want to use the toggle button group to make it look like the picture below.

enter image description here

However, if I insert a button into the toggleButton Group, the size of the button becomes very small. Even if the absolute size is given to each layout, only the size of the toggle Button Group is enlarged and the button inside is small, so I can't see it. When you take out the button, it returns to its normal size and you can see it well, but it looks small only in the group.
Can I know the reasons about this?

答:
I am guessing that there must be separate styles in the toggleButton Group itself for buttons. Maybe you wanna check that.
Another reason I'm thinking is that maybe you have the width of the button set with % percentage, or with vh/vw(view height/width). If so button will change its size relative to the parent element size.</p>


问:
RubyMine dont support rbs
I want to try RBS in RubyMine,so I follow this link: https://www.jetbrains.com/help/ruby/rbs.html

but in my RubyMine,rbs not work
rbs not work

in video there's new rbs file but no in my RubyMine
no menu

my RubyMine version: 2021.3.2
ruby version:3.10
OS:MacOS 12.1

thanks

答: The behaviour has changed slightly. RBS is bundled and included as an External library unless it’s included in the Gemfile. Features like the “New RBS file” aren't shown unless the user has it in their Gemfile as that means they actually want to use it.</p>

Title: RubyMine dont support rbs


问:
How to define a unique field in mongoose schema?
My Schema is like below:

```<code>const schema = new mongoose.Schema({
    a: {
        b: { type: String, unique: true },
        c: { type: String }
    },
    aa: {
        bb: [{
            cc: { type: String, unique: true },
            dd: { type: String }
        }]
    }
})
</code>```

now I want to 'b' and 'cc' fields be unique.
how can i do this?

I added this code at the end of the top code, but the schema allows duplicate values.

```<code>schema.index({'a.b':1}, {unique:true})
schema.index({'aa.bb.cc':1, {unique:true})
</code>```

Do you have any idea to solve this problem?

答:
try adding dropDups as shown below.

```<code>const schema = new mongoose.Schema({
a: {
    b: { type: String, unique: true, dropDups: true },
    c: { type: String }
},
aa: {
    bb: [{
        cc: { type: String, unique: true, dropDups: true },
        dd: { type: String }
    }]
}
</code>```

})

if it doesn't work try: -

```<code>const schema = new mongoose.Schema({
a: {
    b: { type: String, index: { unique: true, dropDups: true } },
    c: { type: String }
},
aa: {
    bb: [{
        cc: { type: String, index: { unique: true, dropDups: true } },
        dd: { type: String }
    }]
}
</code>```

})

Body:
My Schema is like below:

const schema = new mongoose.Schema({
    a: {
        b: { type: String, unique: true },
        c: { type: String }
    },
    aa: {
        bb: [{
            cc: { type: String, unique: true },
            dd: { type: String }
        }]
    }
})

now I want to 'b' and 'cc' fields be unique.
how can i do this?

I added this code at the end of the top code, but the schema allows duplicate values.

schema.index({'a.b':1}, {unique:true})
schema.index({'aa.bb.cc':1, {unique:true})

Do you have any idea to solve this problem?

Body:
try adding dropDups as shown below.

const schema = new mongoose.Schema({
a: {
    b: { type: String, unique: true, dropDups: true },
    c: { type: String }
},
aa: {
    bb: [{
        cc: { type: String, unique: true, dropDups: true },
        dd: { type: String }
    }]
}

})

if it doesn't work try: -

const schema = new mongoose.Schema({
a: {
    b: { type: String, index: { unique: true, dropDups: true } },
    c: { type: String }
},
aa: {
    bb: [{
        cc: { type: String, index: { unique: true, dropDups: true } },
        dd: { type: String }
    }]
}

})


问:
Getting Employee Details and Gender
```<code>select employees.emp_no, employees.birth_date, employees.first_name, employees.last_name,
case
when dept_manager.emp_no IS NOT NULL THEN 'Manager' ELSE 'Employee' END AS Is_Manager
from employees
WHEN employees.gender = 'M' THEN 'Male' ELSE 'Female' END AS 'Gender'
LEFT JOIN
dept_manager ON  dept_manager.emp_no = employees.emp_no;
</code>```

I wanted to get employees with their gender and whether manager or not. I thought I could use CASE with two conditions. On introducing the second condition I got an EOF error. Kindly help check what could be wrong with my code.

答:
This should work</p>
```<code>select employees.emp_no, employees.birth_date, employees.first_name, employees.last_name,
(case when dept_manager.emp_no IS NOT NULL THEN 'Manager'
ELSE 'Employee' END)Is_Manager
(case when employees.gender = 'M' THEN 'Male' ELSE 'Female' END)Gender
from employees
LEFT JOIN
dept_manager ON  dept_manager.emp_no = employees.emp_no;
</code>```

Title: Getting Employee Details and Gender

Body:
select employees.emp_no, employees.birth_date, employees.first_name, employees.last_name,
case
when dept_manager.emp_no IS NOT NULL THEN 'Manager' ELSE 'Employee' END AS Is_Manager
from employees
WHEN employees.gender = 'M' THEN 'Male' ELSE 'Female' END AS 'Gender'
LEFT JOIN
dept_manager ON  dept_manager.emp_no = employees.emp_no;

I wanted to get employees with their gender and whether manager or not. I thought I could use CASE with two conditions. On introducing the second condition I got an EOF error. Kindly help check what could be wrong with my code.

Body:
This should work

select employees.emp_no, employees.birth_date, employees.first_name, employees.last_name,
(case when dept_manager.emp_no IS NOT NULL THEN 'Manager'
ELSE 'Employee' END)Is_Manager
(case when employees.gender = 'M' THEN 'Male' ELSE 'Female' END)Gender
from employees
LEFT JOIN
dept_manager ON  dept_manager.emp_no = employees.emp_no;


问:
How to use slash commands in discord.py
I am trying to make a discord bot which gives Google drive sharable link using slash command

When I type "/bot notes" it should display these choices

```<code>sub= ["ac","cal","emi","pc"]
</code>```

it should display these sub choices for respective  items

```<code>ac=["cat1","cat2","cb1","cb2"]

</code>```

and similarly for others too it should display the sub chioces
after choosing any sub command the bot should give the link.
But the problem is that how should I use slash command and provide choices and sub-choices ?

答:
I'm really not sure what exactly you're getting at here. If you're talking about arguments, then slash commands come with autocomplete.

You could start by making a function

```<code>async def notes(ctc: discord.AutocompleteContext):
    return ["ac","cal","emi","pc"]
</code>```

and then passing this as an autocomplete like this:

```<code>bot = discord.Bot()
@bot.slash_command(description="test", autocomplete=notes)
</code>```

Title: How to use slash commands in discord.py

Body:
I am trying to make a discord bot which gives Google drive sharable link using slash command

When I type "/bot notes" it should display these choices

sub= ["ac","cal","emi","pc"]

it should display these sub choices for respective  items

ac=["cat1","cat2","cb1","cb2"]

and similarly for others too it should display the sub chioces
after choosing any sub command the bot should give the link.
But the problem is that how should I use slash command and provide choices and sub-choices ?

Body:
I'm really not sure what exactly you're getting at here. If you're talking about arguments, then slash commands come with autocomplete.

You could start by making a function

async def notes(ctc: discord.AutocompleteContext):
    return ["ac","cal","emi","pc"]

and then passing this as an autocomplete like this:

bot = discord.Bot()
@bot.slash_command(description="test", autocomplete=notes)


问:
How to roll the rows of a Eigen:Matrix?
I want to reindex a Eigen:Matrix by rolling N∈ℤ rows like this (here N=+1):

```
1 4 7  ->  3 6 9
2 5 8      1 4 7
3 6 9      2 5 8
```

Is there a simple way, or do I have to create a new matrix and copy over the data?

答:
I suggest setting up a new matrix and copying the data. Eigen's block operations allow doing this in an efficient way. Here is how a shift by n rows can be done for the example above.

```<code>MatrixXi A(3,3);
A << 1, 2, 3, 4, 5, 6, 7, 8, 9;
A.transposeInPlace();
int n = 1; // number of shifts
n = n % A.rows();

MatrixXi B(A.rows(), A.cols());
B.bottomRows(A.rows() - n) = A.topRows(A.rows() - n);
B.topRows(n) =  A.bottomRows(n);

std::cout << "B = " << B << std::endl;
</code>```

Title: How to roll the rows of a Eigen:Matrix?

Body:
I want to reindex a Eigen:Matrix by rolling N∈ℤ rows like this (here N=+1):

1 4 7  ->  3 6 9
2 5 8      1 4 7
3 6 9      2 5 8

Is there a simple way, or do I have to create a new matrix and copy over the data?

Body:
I suggest setting up a new matrix and copying the data. Eigen's block operations allow doing this in an efficient way. Here is how a shift by n rows can be done for the example above.

MatrixXi A(3,3);
A << 1, 2, 3, 4, 5, 6, 7, 8, 9;
A.transposeInPlace();
int n = 1; // number of shifts
n = n % A.rows();

MatrixXi B(A.rows(), A.cols());
B.bottomRows(A.rows() - n) = A.topRows(A.rows() - n);
B.topRows(n) =  A.bottomRows(n);

std::cout << "B = " << B << std::endl;


问:
Why is the sum() sql function not working?
I am trying to write a code that collects all the data in a column named AMOUNT in a table named PERSON and I used the function sum() and I got an error java.sql.SQLException: There is no column named: SUM(AMOUNT).

my code is:

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   Connection con = null;
   ResultSet rs = null;
   PreparedStatement ps = null;
   try{
       String sql ="SELECT SUM(AMOUNT) FROM PERSON";
       con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices","user1","user1");
       ps = con.prepareStatement(sql);
       rs=ps.executeQuery();
       if(rs.next()){
       String sum=rs.getString("SUM(AMOUNT)");
       jLabel3.setText(sum);
       }
    }
       catch(Exception ex){
       ex.printStackTrace();
}
</code>```

The error is

java.sql.SQLException: There is no column named: SUM(AMOUNT).

答:
Replace

```<code>String sql ="SELECT SUM(AMOUNT) FROM PERSON";
</code>```

as

```<code>String sql ="SELECT SUM(AMOUNT) AS sumAmount FROM PERSON";  // Use a alias.
</code>```

Then

```<code>String sum=rs.getString("sumAmount");
</code>```

Body:
I am trying to write a code that collects all the data in a column named AMOUNT in a table named PERSON and I used the function sum() and I got an error java.sql.SQLException: There is no column named: SUM(AMOUNT).

my code is:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   Connection con = null;
   ResultSet rs = null;
   PreparedStatement ps = null;
   try{
       String sql ="SELECT SUM(AMOUNT) FROM PERSON";
       con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices","user1","user1");
       ps = con.prepareStatement(sql);
       rs=ps.executeQuery();
       if(rs.next()){
       String sum=rs.getString("SUM(AMOUNT)");
       jLabel3.setText(sum);
       }
    }
       catch(Exception ex){
       ex.printStackTrace();
}

The error is

java.sql.SQLException: There is no column named: SUM(AMOUNT).

Body:
Replace

String sql ="SELECT SUM(AMOUNT) FROM PERSON";

as

String sql ="SELECT SUM(AMOUNT) AS sumAmount FROM PERSON";  // Use a alias.

Then

String sum=rs.getString("sumAmount");


答:
The query is syntactically wrong.

FROM clause needs to go after all the list of columns in SELECT clause.

When you added the second condition for a new column Gender, you also needed to write the keyword CASE before the WHEN condition.

Below is the correct syntax:

```<code>SELECT employees.emp_no, employees.birth_date, employees.first_name, employees.last_name,
CASE WHEN dept_manager.emp_no IS NOT NULL THEN 'Manager' ELSE 'Employee' END AS Is_Manager,
CASE WHEN employees.gender = 'M' THEN 'Male' ELSE 'Female' END AS Gender
FROM employees
LEFT JOIN
dept_manager ON  dept_manager.emp_no = employees.emp_no;
</code>```

Here is an answer on how to use the CASE syntax in SQL.

Title: Getting Employee Details and Gender

Body:
The query is syntactically wrong.

FROM clause needs to go after all the list of columns in SELECT clause.

When you added the second condition for a new column Gender, you also needed to write the keyword CASE before the WHEN condition.

Below is the correct syntax:

SELECT employees.emp_no, employees.birth_date, employees.first_name, employees.last_name,
CASE WHEN dept_manager.emp_no IS NOT NULL THEN 'Manager' ELSE 'Employee' END AS Is_Manager,
CASE WHEN employees.gender = 'M' THEN 'Male' ELSE 'Female' END AS Gender
FROM employees
LEFT JOIN
dept_manager ON  dept_manager.emp_no = employees.emp_no;

Here is an answer on how to use the CASE syntax in SQL.


问:
Thread 1: "+[UIImage systemImageNamed:]: unrecognized selector sent to class 0x111e616e0"
Thread 1: "+[UIImage systemImageNamed:]: unrecognized selector sent to class 0x111e616e0"

This error occurs in app delegate when trying to run my application in iOS 12 iphone 6s but its working normally in iOS 13+ devices  Error text shown in XCode

答:
The reason behind crash is SFSymbol is only available on iOS 13 and above version.

```<code>UIImage(systemName: "") -> It will crash on iOS 12 and below version.
</code>```

If you want to use SFsymbol in iOS 12 and below version then check this URL

How to use SF Symbols in iOS 12 and below?

Body:
The reason behind crash is SFSymbol is only available on iOS 13 and above version.

UIImage(systemName: "") -> It will crash on iOS 12 and below version.

If you want to use SFsymbol in iOS 12 and below version then check this URL

How to use SF Symbols in iOS 12 and below?


问:
process items in Generic list/collections with Reflection
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute.  I am recursing into each property to do the same for each of their properties.  My issue is when I come to some sort of collection property (property that is a collection) or ICollection property.  I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables).

Here is some code to help understand a little more:

```<code> public class NotificationMessageProcessor<T> : INotificationProcessor<T>
    {
          IList<string> availableTags = new List<string>();

          public string ReplaceNotificationTags<T>(string message, T instance)
          {

             LoadTagValues(instance);
             return ReplaceTags(message);

          }

          private string ReplaceTags(string message)
          {
             foreach (KeyValuePair<string, string> tagVal in tagValues)
             {
                 message = message.Replace(string.Format("<{0}>", tagVal.Key),     tagVal.Value);
             }
             return message;
          }

          private void LoadTagValues(object val)
          {
              Type elementType = val.GetType();
              PropertyInfo[] typeProperties = elementType.GetProperties();
              foreach (PropertyInfo prop in typeProperties)
              {

                 NotificationTag[] tags =      (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false);
                if (tags != null && tags.Length > 0)
                {
                    string tagName = tags[0].TagName;
                    object propValue = prop.GetValue(val, null);
                    string propTypeString = prop.PropertyType.FullName;
                    tagName = prop.ReflectedType.Name + "." + tagName;
                    if (propValue != null)
                    {
                      tagValues.Add(tagName, propValue.ToString());
                    }

                    if (propValue != null)
                    {
                       if (!prop.PropertyType.IsPrimitive)
                       {
                         LoadTagValues(propValue);
                       }
                    }
                }
                else
                {
                   if (!prop.PropertyType.IsPrimitive)
                   {
                     object propValue = null;

                        if (prop.GetGetMethod().GetParameters().Count() == 0)
                        {
                            propValue = prop.GetValue(val, null);
                        }
                        else
                        {
                           //have a collection...need to process but do not know how many in collection....
                                propValue = prop.GetValue(val, new object[] { 0 });

                        }
                    if (propValue != null)
                    {
                        LoadTagValues(propValue);
                    }
                }
            }
        }
    }

 NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor();
    userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser);
</code>```

The User object has the proper attributes

答: I am doing the cast to IEnumerable, I was trying to cast the wrong object when I was having issues.</p>

OwnerDisplayName: CSharpAtl

Body:
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute.  I am recursing into each property to do the same for each of their properties.  My issue is when I come to some sort of collection property (property that is a collection) or ICollection property.  I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables).

Here is some code to help understand a little more:

 public class NotificationMessageProcessor<T> : INotificationProcessor<T>
    {
          IList<string> availableTags = new List<string>();

          public string ReplaceNotificationTags<T>(string message, T instance)
          {

             LoadTagValues(instance);
             return ReplaceTags(message);

          }

          private string ReplaceTags(string message)
          {
             foreach (KeyValuePair<string, string> tagVal in tagValues)
             {
                 message = message.Replace(string.Format("<{0}>", tagVal.Key),     tagVal.Value);
             }
             return message;
          }

          private void LoadTagValues(object val)
          {
              Type elementType = val.GetType();
              PropertyInfo[] typeProperties = elementType.GetProperties();
              foreach (PropertyInfo prop in typeProperties)
              {

                 NotificationTag[] tags =      (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false);
                if (tags != null && tags.Length > 0)
                {
                    string tagName = tags[0].TagName;
                    object propValue = prop.GetValue(val, null);
                    string propTypeString = prop.PropertyType.FullName;
                    tagName = prop.ReflectedType.Name + "." + tagName;
                    if (propValue != null)
                    {
                      tagValues.Add(tagName, propValue.ToString());
                    }

                    if (propValue != null)
                    {
                       if (!prop.PropertyType.IsPrimitive)
                       {
                         LoadTagValues(propValue);
                       }
                    }
                }
                else
                {
                   if (!prop.PropertyType.IsPrimitive)
                   {
                     object propValue = null;

                        if (prop.GetGetMethod().GetParameters().Count() == 0)
                        {
                            propValue = prop.GetValue(val, null);
                        }
                        else
                        {
                           //have a collection...need to process but do not know how many in collection....
                                propValue = prop.GetValue(val, new object[] { 0 });

                        }
                    if (propValue != null)
                    {
                        LoadTagValues(propValue);
                    }
                }
            }
        }
    }

 NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor();
    userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser);

The User object has the proper attributes

LastEditorDisplayName: CSharpAtl


问:
How can i run a propery in logic app for each only first run of the loop?
Is it possible to remove a property after the first run in the foreach loop, i want to remove the property "pickedQuantity".

答:
To remove properties from an object you can use

removeProperty function
https://learn.microsoft.com/en-us/azure/logic-apps/workflow-definition-language-functions-reference#removeProperty

But not sure how this is possible in your loop. If you always want to remove it after the first run, why not do the first "run" outside the loop, then loop the rest?


问:
How do I make an offline backup of a Snowflake database?
I have an application that used to run on Snowflake but was migrated to a SQL Managed Instance. i used SnowHub to export all the DDL and then zipped it up should I ever need to look up some source code for a deprecated report or other process.

But how do dump the entire database to a compressed file. You never know when an audit might come up and I might need to restore the data in the state it was a few months or years ago.

答:
You have to use UNLOADING to load data from your table to an internal/external stage in your preferred format.

https://docs.snowflake.com/en/user-guide/data-unload-overview.html

Unfortunately, you cannot unload the whole database with one statement, but need to run one COPY INTO  per table. As an alternative you could write a procedure looping over your metadata about tables and run COPY INTO  per loop execution.


问:
Longest Consecutive Subsequence in a stream of integers
Given a stream of array, for each element we have to find the longest consecutive subsequence till now

For example:

10 -> 1

12 -> 1

11 -> 3 (10,11,12)

20 -> 3

What I think: Create a set and for each incoming number, check what if its the start/end of the LCS. Take the max possible length.

Since this is of O(N^2), is there any possible way to reduce the TC? I don't need the code but just a way to optimize the algo

答:
You can do this in O(n log n) time with a balanced BST using the ideas from this post.

An incoming number x will be treated as an interval [x, x+1]. The BST stores the boundary points of the disjoint intervals; each leaf node in the BST should also store whether it's a start or end, and the length of the interval it's part of.

When a point x comes in, search the BST for the largest element u <= x. If it's present and it's a 'start point', continue. Also search for the smallest element x + 1 <= v. If it's present and it's an 'end point', continue.

Otherwise, there's several cases. If x is an end point and x+1 is a start point, you should remove both from the BST, forming a new interval whose size is the sum of the two combined intervals + 1. If one of (x is an end point, x+1 is a start point) is true, remove that point, and extend the appropriate interval by 1 to the right or left, respectively. If [x, x+1] is already contained in an interval, continue. Otherwise, add x and x+1 to the BST as a start and end, respectively, of size 1.

On each addition, you'll check whether the new interval is larger than the previous largest: if so, and u, v are the boundary points, your longest consecutive subsequence is u, u+1, ... v-1.


问:
How to get the key and value from map and perform certain operation on each key and value using Java8 methods
How to get the key and value from map and perform certain operation on each key and value using Java8 methods

I got some methods but it helps only to print the message(using System.out.println),but I want to perform some operations(finding duplicates in value,comparing values using casting etc.,) in each key/value pair

Map<String,String> l_map=new TreeMap<String,String>();

Thanks in advance!

答:
you can use the forEach() function of the map, and get a key and value during each iteration by using a lambda expression.</p>
```<code>Map<String,String> l_map=new TreeMap<String,String>();
    l_map.forEach( (key, value) -> {
        key="";
        value="";
    });
</code>```

Body:
you can use the forEach() function of the map, and get a key and value during each iteration by using a lambda expression.

Map<String,String> l_map=new TreeMap<String,String>();
    l_map.forEach( (key, value) -> {
        key="";
        value="";
    });


问:
Generate 4 digits number but excluding all the numbers with any 0
I would like to generate 4 digits random number in Python but exclude all the numbers that have a "0" inside. For example, 9230, 2012 will not be accepted since there is a 0.

My code is:

```<code>def my_custom_random():
    exclude=[0]
    randInt = randint(1000, 9999)
    return my_custom_random() if randInt in exclude else randInt

def Q3a():
      RandomNumber = my_custom_random())
      print(RandomNumber)

Q3a()
</code>```

But this code is not working. Anyone can help me ? Thanks.

答:
I hope it will help you

```<code>    import random

    def my_custom_random():
        exclude = 0
        digits = [0,1,2,3,4,5,6,7,8,9]
        randNumber = random.sample(digits,4) #List of integers Ex. [2,9,1,6]
        while exclude in randNumber:
            randNumber = random.sample(digits,4)
        return map(str,randNumber) #map(str, x) -> transform [2,9,1,6] to ['2','9','1','6']

    def Q3a():
        randNumber = my_custom_random()
        randNumber = "".join(randNumber) # ['2','9','1','6'] to '2916'
        print(int(randNumber))

    Q3a()
</code>```

In digits you can omit the 0, so you can write less code. This way you will never have numbers with zero.

```<code>    def my_custom_random():
        digits = [1,2,3,4,5,6,7,8,9]
        randNumber = random.sample(digits,4)
        return map(str,randNumber)
</code>```

Body:
I would like to generate 4 digits random number in Python but exclude all the numbers that have a "0" inside. For example, 9230, 2012 will not be accepted since there is a 0.

My code is:

def my_custom_random():
    exclude=[0]
    randInt = randint(1000, 9999)
    return my_custom_random() if randInt in exclude else randInt

def Q3a():
      RandomNumber = my_custom_random())
      print(RandomNumber)

Q3a()

But this code is not working. Anyone can help me ? Thanks.

Body:
I hope it will help you

    import random

    def my_custom_random():
        exclude = 0
        digits = [0,1,2,3,4,5,6,7,8,9]
        randNumber = random.sample(digits,4) #List of integers Ex. [2,9,1,6]
        while exclude in randNumber:
            randNumber = random.sample(digits,4)
        return map(str,randNumber) #map(str, x) -> transform [2,9,1,6] to ['2','9','1','6']

    def Q3a():
        randNumber = my_custom_random()
        randNumber = "".join(randNumber) # ['2','9','1','6'] to '2916'
        print(int(randNumber))

    Q3a()

In digits you can omit the 0, so you can write less code. This way you will never have numbers with zero.

    def my_custom_random():
        digits = [1,2,3,4,5,6,7,8,9]
        randNumber = random.sample(digits,4)
        return map(str,randNumber)


问:
Size cannot be resolved to a type
Size annotation is not found and I get Size cannot be resolved to a type .Although import javax.validation.constraints.Size; is added I get this error.

import javax.validation.constraints.Size;

import lombok.Data;

@Data public class UserCreateDTO {        @Size   private String firstName;
private String lastName;

}

My dependencies in POM.xml are:

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

答:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#validation-starter-no-longer-included-in-web-starters

Validation Starter no longer included in web starters
As of #19550, Web and WebFlux starters do not depend on the validation starter by default anymore. If your application is using validation features, for example you find that javax.validation.* imports are not being resolved, you’ll need to add the starter yourself.

For Maven builds, you can do that with the following:

```<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</code>```

For Gradle, you will need to add something like this:

```<code>dependencies {
  ...
  implementation 'org.springframework.boot:spring-boot-starter-validation'
}
</code>```

Title: Size cannot be resolved to a type

Body:
Size annotation is not found and I get Size cannot be resolved to a type .Although import javax.validation.constraints.Size; is added I get this error.

import javax.validation.constraints.Size;

import lombok.Data;

@Data public class UserCreateDTO {        @Size   private String firstName;
private String lastName;

}

My dependencies in POM.xml are:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Body:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#validation-starter-no-longer-included-in-web-starters

Validation Starter no longer included in web starters
As of #19550, Web and WebFlux starters do not depend on the validation starter by default anymore. If your application is using validation features, for example you find that javax.validation.* imports are not being resolved, you’ll need to add the starter yourself.

For Maven builds, you can do that with the following:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

For Gradle, you will need to add something like this:

dependencies {
  ...
  implementation 'org.springframework.boot:spring-boot-starter-validation'
}


问:
Visual Studio Code is changing HTML after saving (React)
I started to  learn react. A few minutes later messed up. I was looking for a setting and somehow I come where else where i selected a different choice(something like NodeJS)...now my problem is:

First Image

Second Image

First image is what I wrote. Second image is what it became after saving(CTRL + S).

Third Image

This third image is the changed original template...

I tried to reinstall VS Code and deleting the settings(user/json) file nothing has changed. Does anyone know how to fix this problem.

Any help is appreciated :P

答: their is different formatter for react. but for instant fix just disable auto formating on save from vscode setting.


问:
How to swap words in strings
I have a string in my code like:

val string = "
|3
|3{{P|Mummy Zombie|2}}5 {{P|Mummy Zombie|2}}
|None
"
```
<p>The sample code is shorter, will have more <code><sup></sup></code> {{zombie}} and the mummy zombie might be like conehead zombie, buckethead zombie... there is like a hundred types of zombies</p>
<p>how can i change it to like:</p>
<pre class="lang-kotlin prettyprint-override"><code>"
|3
|{{P|Mummy Zombie|2}}<sup>3</sup> {{P|Mummy Zombie|2}}<sup>5</sup>
|None
"
</code>```

Title: How to swap words in strings

Body:
I have a string in my code like:

val string = "
|3
|3{{P|Mummy Zombie|2}}5 {{P|Mummy Zombie|2}}
|None
"

The sample code is shorter, will have more  {{zombie}} and the mummy zombie might be like conehead zombie, buckethead zombie... there is like a hundred types of zombies

how can i change it to like:

"
|3
|{{P|Mummy Zombie|2}}3 {{P|Mummy Zombie|2}}5
|None
"

Body:
If you don't mind regex:

val s = """
|3
|<sup>3</sup>{{P|Mummy Zombie|2}}<sup>5</sup> {{P|Mummy Zombie|2}}
|None
"""
val regex = "(<[^>]+>[^>]+>)\\s*(\\{\\{[^}]+\\}\\})".toRegex()
println(s.replace(regex, "$2$1"))


答:
not sure what you are trying to achieve.

Are you sniffing the traffic between your device and IoT Hub over the wire?
This is encrypted as all the comm toward IoT Hub uses TLS.

Do you want to support the AMQP protocol for a device that can't use one of the IoT hub SDKs?

In this case, if you can use an AMQP library, I would suggest to have a look at this document: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-amqp-support. That document describes how IoT Hub leverage the AMQP protocol to abstract the IoT Hub messaging patterns (D2C, C2D, Direct Methods and Twin updates).

Nevertheless, if you are writing an iot device agent / firmware, I would probably suggest to start with MQTT as a protocol, way simpler especially if you can't use SKDs.

Title: Azure IOT Decode Amqp Messages From Web Socket (Hexadecimal string)

Body:
I'm trying to decode AMQP messages sended and revived between Azure IoT Edge and Azure Hub.
At this moment I can read the data inside the socket, having something like this:

Now, I'd like to see this packages as json or object or something that a human could read.

Binary    Thu Jan 27 10:02:19 CET 2022    Thu Jan 27 10:02:19 CET 2022    414D
5150 0001 0000

Binary    Thu Jan 27 10:02:19 CET 2022    Thu Jan 27 10:02:19 CET 2022    0000
005D 0200 0000 0053 10C0 500A A120 6532 3461 3963 3238 3332 3139 3464
3130 3830 3938 3835 6364 6539 6637 6130 6662 A119 696F 746D 616E 752E
617A 7572 652D 6465 7669 6365 732E 6E65 7470 0001 0000 601F FF70 0000
EA60 4040 4040 40

Binary    Thu Jan 27 10:02:19 CET 2022    Thu Jan 27 10:02:19 CET 2022    0000
0025 0200 0000 0053 11C0 1808 4052 0170 0000 1388 7000 0013 8870 0003
FFFF 4040 C101 00 Binary  Thu Jan 27 10:02:20 CET 2022    Thu Jan 27
10:02:20 CET 2022 0000 0025 0200 0001 0053 11C0 1808 4052 0170 0000
1388 7000 0013 8870 0003 FFFF 4040 C101 00

Binary    Thu Jan 27 10:02:20 CET 2022    Thu Jan 27 10:02:20 CET 2022    0000
0072 0200 0001 0053 12C0 650E A115 6475 706C 6578 3337 3A33 393A 3430
3A73 656E 6465 7243 4250 0140 0053 28C0 0C0B 4040 4040 4040 4040 4040
4000 5329 C00D 07A1 0424 6362 7340 4040 4040 4040 4040 4040 40C1 1D02
A315 636F 6D2E 6D69 6372 6F73 6F66 743A 7469 6D65 6F75 7470 0000 E6E7

Any help to decode this?
Thanks in advance.


问:
NestJs async httpService call
How can I use Async/Await on HttpService using NestJs?
The below code doesn`t works:

```<code>async create(data) {
    return await this.httpService.post(url, data);
}
</code>```

答:
try these below one instead of only async-await.

There are some basic reasons behind the deprecation of toPromise.

We know that Promise and Observables that both collections may produce values over time.
where  Observables return none or more and Promise return only one value when resolve successfully.

there is a main reason behind the seen

Official: https://rxjs.dev/deprecations/to-promise

Stack:Rxjs toPromise() deprecated

Now we have 2 new functions.

lastValueFrom : last value that has arrived when the Observable completes for more https://rxjs.dev/api/index/function/firstValueFrom

firstValueFrom:  you might want to take the first value as it arrives without waiting an Observable to complete for more https://rxjs.dev/api/index/function/lastValueFrom

Title: NestJs async httpService call

Body:
How can I use Async/Await on HttpService using NestJs?
The below code doesn`t works:

async create(data) {
    return await this.httpService.post(url, data);
}


问:
every time loop is finished return something C#
hi I Want to loop over a data and each time it's iterating return something. I know if if use return inside loop the loop will be finished is there any other way. Thanks for helping.

some thing like this

reply to kevinSpaceyIsKeyserSöze
no it's like a list of data when user clicks post it should remove the ones which are finished from list or send a msg like remove data where id == id and i could remove it from list in angular front-end

let me show you the real code what i want

```<code> foreach (var item in data)
        {
            var FileName = Guid.NewGuid().ToString() + "_" + item.CustomerName + ".pdf";
            var filePath = root + FileName;
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create pdf file
                var doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
                PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                doc.Open();
                doc.Add(new iTextSharp.text.Paragraph(item.Data));
                doc.Close();
                // create pdf file ended

                // send email
                sendEmail(item.CustomerName, filePath);
                // in here i want to send back a response that the file with id item.id is created so remove it from table
            }
        }
</code>```

答:
It's not completely clear what you're trying to do, but if you let the script loop in a different thread then after sendEmail() you could trigger an event which get caught by the main thread?

Or when you have a datagrid and remove the value, it gets deleted real time?

Body:
hi I Want to loop over a data and each time it's iterating return something. I know if if use return inside loop the loop will be finished is there any other way. Thanks for helping.

some thing like this

reply to kevinSpaceyIsKeyserSöze
no it's like a list of data when user clicks post it should remove the ones which are finished from list or send a msg like remove data where id == id and i could remove it from list in angular front-end

let me show you the real code what i want

 foreach (var item in data)
        {
            var FileName = Guid.NewGuid().ToString() + "_" + item.CustomerName + ".pdf";
            var filePath = root + FileName;
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                // create pdf file
                var doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
                PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                doc.Open();
                doc.Add(new iTextSharp.text.Paragraph(item.Data));
                doc.Close();
                // create pdf file ended

                // send email
                sendEmail(item.CustomerName, filePath);
                // in here i want to send back a response that the file with id item.id is created so remove it from table
            }
        }


问:
Getting attribute's value in Nokogiri to extract link URLs
I have a document which look like this:

```<code><div id="block">
    <a href="http://google.com">link</a>
</div>
</code>```

I can't get Nokogiri to get me the value of href attribute. I'd like to store the address in a Ruby variable as a string.

答:
```<code>html = <<HTML
  <div id="block">
    <a href="http://google.com">link</a>
  </div>
HTML
doc = Nokogiri::HTML(html)
doc.xpath('//div/a/@href')
#=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
</code>```

Or if you wanna be more specific about the div:

```<code>>> doc.xpath('//div[@id="block"]/a/@href')
=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
>> doc.xpath('//div[@id="block"]/a/@href').first.value
=> "http://google.com"
</code>```

Body:
I have a document which look like this:

    link

I can't get Nokogiri to get me the value of href attribute. I'd like to store the address in a Ruby variable as a string.

Body:
html = <<HTML
  <div id="block">
    <a href="http://google.com">link</a>
  </div>
HTML
doc = Nokogiri::HTML(html)
doc.xpath('//div/a/@href')
#=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]

Or if you wanna be more specific about the div:

>> doc.xpath('//div[@id="block"]/a/@href')
=> [#<Nokogiri::XML::Attr:0x80887798 name="href" value="http://google.com">]
>> doc.xpath('//div[@id="block"]/a/@href').first.value
=> "http://google.com"


问:
Getting all selected values in Bootstrap5 Form.Control
I'm trying to get all selected values from a react-bootstrap Form. On the latest version of bootstrap e.target.value only seems to contain a single value instead of a list when multiple values are selected by shift clicking multiple lines. How can I get all selected values? Preferably by key or id.

```<code>const Form = ReactBootstrap.Form;
const Button = ReactBootstrap.Button;

const ExampleForm = () => {

  const [output, setOutput] = React.useState("");

  function changeSelection(e) {
    setOutput(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
  }

  return(

    <Form onSubmit={handleSubmit}>
      <Form.Group controlId="dimension">
        <Form.Control
          as="select"
          multiple
          onChange={changeSelection}>
          <option key="1" id="1" >1</option>
          <option key="2" id="2" >2</option>
          <option key="3" id="3" >3</option>
          <option key="4" id="4" >4</option>
        </Form.Control>
        <Button type="submit" variant="primary">
                select
        </Button>
      </Form.Group>
      Output: {output}
    </Form>

  );

}

ReactDOM.render(
    <ExampleForm />,
    document.getElementById('app')
);

</code>```

Codepen example can be found here

答:
Turns out you can use Array.from

```<code>Array.from(e.target.selectedOptions, option => option.value)
</code>```

Found here

Body:
I'm trying to get all selected values from a react-bootstrap Form. On the latest version of bootstrap e.target.value only seems to contain a single value instead of a list when multiple values are selected by shift clicking multiple lines. How can I get all selected values? Preferably by key or id.

const Form = ReactBootstrap.Form;
const Button = ReactBootstrap.Button;

const ExampleForm = () => {

  const [output, setOutput] = React.useState("");

  function changeSelection(e) {
    setOutput(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
  }

  return(

    <Form onSubmit={handleSubmit}>
      <Form.Group controlId="dimension">
        <Form.Control
          as="select"
          multiple
          onChange={changeSelection}>
          <option key="1" id="1" >1</option>
          <option key="2" id="2" >2</option>
          <option key="3" id="3" >3</option>
          <option key="4" id="4" >4</option>
        </Form.Control>
        <Button type="submit" variant="primary">
                select
        </Button>
      </Form.Group>
      Output: {output}
    </Form>

  );

}

ReactDOM.render(
    <ExampleForm />,
    document.getElementById('app')
);

Codepen example can be found here

Body:
Turns out you can use Array.from

Array.from(e.target.selectedOptions, option => option.value)

Found here


问:
Laravel 8 Query builder update does not seem to work
I have this query that I'm trying to execute to update multiple rows in my database(Postgres). It seems to have worked at first since there was no error but the records that I'm trying to update were not affected.

This is the query:

```<code>DB::table('trea.close_account_track')
            ->where('year', $fin_year)
            ->where('month', $month)
            ->whereIn('trea_code', $trea_code)
            ->where('status', 'Y')
            ->update(['ag_download_status' => 'Y']);
</code>```

And here's the generated SQL:

```<code>array (
    'query' => 'update "trea"."close_account_track" set "ag_download_status" = ? where "year" = ? and "month" = ? and "trea_code" in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and "status" = ?',
    'bindings' =>
    array (
      0 => 'Y',
      1 => '2022',
      2 => '1',
      3 => '02',
      4 => '03',
      5 => '10',
      6 => '11',
      7 => '20',
      8 => '30',
      9 => '31',
      10 => '32',
      11 => '40',
      12 => '41',
      13 => '50',
      14 => '60',
      15 => '70',
      16 => '71',
      17 => '72',
      18 => '80',
      19 => 'Y',
    ),
    'time' => 2.47,
  )
</code>```

If I run the generated SQL manually, the records were changed as expected. I have checked the error logs for both PHP and Postgres but there was also nothing there.

答: I found out that the query builder removes any zeroes from the variable even when it is a string or character hance the mismatch in the where query and therefore not updating appropriately. Case in point, the 3rd element(index 2) is supposed to be 01 but it changed to 1.</p>

Body:
I have this query that I'm trying to execute to update multiple rows in my database(Postgres). It seems to have worked at first since there was no error but the records that I'm trying to update were not affected.

This is the query:

DB::table('trea.close_account_track')
            ->where('year', $fin_year)
            ->where('month', $month)
            ->whereIn('trea_code', $trea_code)
            ->where('status', 'Y')
            ->update(['ag_download_status' => 'Y']);

And here's the generated SQL:

array (
    'query' => 'update "trea"."close_account_track" set "ag_download_status" = ? where "year" = ? and "month" = ? and "trea_code" in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and "status" = ?',
    'bindings' =>
    array (
      0 => 'Y',
      1 => '2022',
      2 => '1',
      3 => '02',
      4 => '03',
      5 => '10',
      6 => '11',
      7 => '20',
      8 => '30',
      9 => '31',
      10 => '32',
      11 => '40',
      12 => '41',
      13 => '50',
      14 => '60',
      15 => '70',
      16 => '71',
      17 => '72',
      18 => '80',
      19 => 'Y',
    ),
    'time' => 2.47,
  )

If I run the generated SQL manually, the records were changed as expected. I have checked the error logs for both PHP and Postgres but there was also nothing there.


问:
How to extract elements of an array in object type in c#?
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
</code>```

答:
You need to cast it back to int[] and then extract the elements. After all, the fact that you know that is an array of integer doesn't reflect the fact that you're stating that is an object.

Look at it from the point of view of the compiler. All he know is that you've defined an object variable that, at that point, happens to be an array of integer, but which could change later on to another thing.. after all is just an object.

The constraints checks are performed by the runtime when you do the cast, so, logically, the compiler won't let you just use it as an array but require you to first CAST it to an array.

Body:
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (of a priory unknown type and I cannot use type conversion in the code
//How can extract elements of obj and use them, e.g. write them on the screen?`