instruction stringlengths 0 30k ⌀ |
|---|
I have a api that only uses POST, so i have to sent an ID to fetch, in this case event.
The problem is that my SWR is making infinite calls.
I have this component:
```
const EventDetail = ({ params }: { params: { id: string } }) => {
const id: string = params.id;
const [cookies] = useCookies(["token"]);
const token = cookies.token;
let formData = new FormData();
formData.append("id", id);
const dataToRequest = { token, formData };
const { data, error, isLoading } = useSWR(
[SERVICESADDR.EVENT, dataToRequest],
fetcher,
);
if (error) {
console.log(error);
}
console.log(data);
return <div>{id}</div>;
};
export default EventDetail;
```
and my fetcher is:
```
export const fetcher = ([url, data]: [
url: string,
data: { token: string; formData?: FormData },
]) =>
fetch(url, {
method: "POST",
body: data.formData,
headers: {
Authorization: `Bearer ${data.token}`,
"Accept-Language": "pt",
Accept: "/*",
},
})
.then((res) => res.text())
.then((res) => res);
```
Thank you in advance!! |
useSWR has infinite service call |
|reactjs|next.js|swr| |
null |
In Python, Delta Live Tables determines whether to update a dataset as a materialized view or streaming table based on the defining query.
The **@table** decorator is used to define both materialized views and streaming tables.
To define a materialized view in Python, apply **@table to a query that performs a static read against a data source**.
To define a streaming table, apply **@table to a query that performs a streaming read** against a data source.
Read more here
https://docs.databricks.com/en/delta-live-tables/python-ref.html#import-the-dlt-python-module
|
{"Voters":[{"Id":22356960,"DisplayName":"pindakazen"}],"DeleteType":1} |
As the first comment already says, you can use commands that can undo themselves. The idea is to have a `Command` class having a `Do` and a `Undo` method.
These methods have a `ICommandContext context` parameter (it can in fact be of any useful type, e.g. `Game`). This is basically your game application. It allows the commands to access and act on the game.
``` c#
public abstract class Command
{
public abstract void Do(ICommandContext context);
public abstract void Undo(ICommandContext context);
}
```
From this abstract class, you derive different commands, e.g., a `PlaceBetCommand`. When `Do` is called, this concrete class must store all the information the `Undo` method needs, to be able to undo the command.
``` c#
public class PlaceBetCommand : Command
{
// Primary constructor
public PlaceBetCommand(/* TODO: add parameters describing the bet */)
{
// TODO: store the parameters
}
public override void Do(ICommandContext context)
{
// TODO: place the bet and possibly store additional information that you will need in Undo.
}
public abstract void Undo(ICommandContext context)
{
// Undo the bet
}
}
```
The reason bet related information is passed as constructor argument(s) is that different commands require different information but the `Do` method has the same parameter for all commands. Alternatively, you could also pass information through properties.
Then you need an undo-stack and possibly a redo-stack (but you didn't ask for a redo functionality).
``` c#
private static readonly Stack<Command> _undoStack = new();
```
Placing a bet would go like this
``` c#
var bet = new PlaceBetCommand(/* pass the required parameters */);
bet.Do(this);
_undoStack.Push(bet);
```
Undoing goes like this:
``` c#
if (_undoStack.Count > 0) {
var command = _undoStack.Pop();
command.Undo(this);
}
```
I will let you figure out the details, as I do not know how you place bets and what other commands you might have.
If you want to be able to undo placing 3 Rs's one-by-one, then split it into three commands and execute and push them separately.
---
If you want a redo function, then you need a redo stack of the same type as the undo stack as well.
When you execute a command, you will have to clear the redo stack, because the commands on this stack become invalid (they are valid only immediately after having undone commands).
When you undo a command, place it on the redo stack.
Redoing a command consists of popping a command from the redo stack and then executing its `Do` method and pushing it on the undo stack.
|
i have problem in Google Colab Deep Learning coding any one help me about this issue Chat GPT fail to solve my error |
|python|keras|google-colaboratory|tensorflow2.0| |
null |
{"OriginalQuestionIds":[19780411],"Voters":[{"Id":5577765,"DisplayName":"Rabbid76","BindingReason":{"GoldTagBadge":"pygame"}}]} |
round(fractions.Fraction("3.50")) yields 4, as one would expect. But round(fractions.Fraction("49886.50")) yields 49886, not 49887. What gives? |
In the python fractions module, why is a result of round() sometimes incorrect? |
|python|rounding|fractions| |
To make those horizontal lines with annotations, RuleMark or RectangleMark can be used. Rectangle marks were used in this example:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/c58FS.png
RectangleMark has a height parameter which was used to create something similar to the thicker lines in Apple's Cardio chart. RectangleMark has multiple inits to create horizontal lines, vertical lines, squares, rectangles and matrices.
A cornerRadius set to 1/2 the height was added to give the horizontal lines round end caps:
RectangleMark(
xStart: .value("Start", weight[0].date, unit: .day),
xEnd: .value("End", weight[2].date, unit: .day),
y: .value("Average", 69.5),
height: 6
)
.foregroundStyle(.gray)
.cornerRadius(3)
Annotations were added to the rectangle marks:
.annotation(position: .top, alignment: .leading, spacing: 4) {
Text("69.5 VO\u{2082} max")
.font(.subheadline)
}
Full code for better context:
struct ContentView: View {
var body: some View {
Chart() {
ForEach(weight) { data in
LineMark(
x: .value("Day", data.date, unit: .day),
y: .value("Weight", data.weight)
)
.foregroundStyle(.pink)
.symbol {
Circle()
.fill(.pink)
.frame(width: 8)
}
}
// Creates horizontal lines
ForEach(lines) { line in
RectangleMark(
xStart: .value("Start", weight[line.start].date, unit: .day),
xEnd: .value("End", weight[line.end].date, unit: .day),
y: .value("Average", line.average),
height: 6
)
.foregroundStyle(line.color)
.cornerRadius(3)
.annotation(position: .top, alignment: line.alignment, spacing: 4) {
Text("\(line.average)\(line.label)")
.font(.subheadline)
}
}
}
.frame(height: 250)
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { _ in
AxisTick()
AxisGridLine()
AxisValueLabel(format: .dateTime.weekday(.abbreviated), centered: true)
}
}
.chartYScale(domain: 67...71)
}
}
// Data Model
struct TestWeight: Identifiable {
var id = UUID()
var weight: Double
var date: Date
init(id: UUID = UUID(), weight: Double, day: Int) {
self.id = id
self.weight = weight
let calendar = Calendar.current
self.date = calendar.date(from: DateComponents(year: 2023, month: 10, day: day))!
}
}
// Test data
var weight: [TestWeight] = [
TestWeight(weight: 69.4, day: 2),
TestWeight(weight: 69.2, day: 3),
TestWeight(weight: 70.0, day: 4),
TestWeight(weight: 69.7, day: 5),
TestWeight(weight: 69.0, day: 6),
TestWeight(weight: 68.8, day: 7),
TestWeight(weight: 68.0, day: 8)
]
//Data Model - data to create lines
struct TestLine: Identifiable {
var start: Int
var end: Int
var average: Double
var label: String
var color: Color
var alignment: Alignment
var id: Int
}
//Test Data - horizontal lines
let lines: [TestLine] = [
TestLine(start: 0, end: 2, average: 69.5, label: " VO\u{2082} max", color: .gray, alignment: .leading, id: 1),
TestLine(start: 3, end: 6, average: 68.8, label: "", color: .red, alignment: .trailing, id: 2)
]
|
### Problem description
I'm writing a python library and I am planning to upload both sdist (.tar.gz) and wheel to PyPI. The [build docs say](https://build.pypa.io/) that running
```
python -m build
```
I get sdist created from the source tree and *wheel created from the sdist*, which is nice since I get the sdist tested here "for free". Now I want to run tests (pytest) against the wheel with multiple python versions. What is the easiest way to do that?
I have been using tox and I see there's an option for [setting package to "wheel"](https://tox.wiki/en/latest/config.html#package):
```
[testenv]
description = run the tests with pytest
package = wheel
wheel_build_env = .pkg
```
But that does not say *how* the wheel is produced. From the tox logs (with `-vvv`) I can see this:
```
.pkg: 760 I exit None (0.01 seconds) /home/niko/code/myproj> python /home/niko/code/myproj/.tox/.tox/lib/python3.10/site-packages/pyproject_api/_backend.py True flit_core.buildapi pid=251971 [tox/execute/api.py:280]
.pkg: 761 W build_wheel> python /home/niko/code/myproj/.tox/.tox/lib/python3.10/site-packages/pyproject_api/_backend.py True flit_core.buildapi [tox/tox_env/api.py:425]
Backend: run command build_wheel with args {'wheel_directory': '/home/niko/code/myproj/.tox/.pkg/dist', 'config_settings': None, 'metadata_directory': None}
```
These are the commands related creating the wheel. So this one uses [tox-dev/pyproject-api](https://github.com/tox-dev/pyproject-api) under the hood. But it is still a bit unclear whether tox
a) creates wheel directly from source tree<br>
b) creates wheel from sdist which is created from source tree in a way which *is identical to* `python -m build`<br>
c) creates wheel from sdist which is created from source tree in a way which *differs from* `python -m build`
## Question
I want to create wheel which is created from sdist which is created from the source tree, and I want to run unit tests against the wheel(s) with multiple python versions. I prefer using `python -m build` for the wheel creation. What would be the idiomatic way to run the tests against the wheel(s) ? Can I use tox for that?
|
How to test the wheel created with "python -m build" against multiple versions of python? |
|python|python-packaging|tox| |
|css|opacity|shadow| |
I get the following result from an SP-API call using CURL within PHP. It is a private app created in Seller Central, and all permissions have been granted. We are just trying to retrieve our data.
Array (
[errors] => Array
(
[0] => Array
(
[code] => Unauthorized
[message] => Access to requested resource is denied.
[details] => Access token is missing in the request header.
)
)
)
An access token is retrieved with a refresh token and included; here is the code. amazonApiUrl is https://sellingpartnerapi-na.amazon.com
```
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer '.$accessToken
);
$curl = curl_init($this->amazonApiUrl."/catalog/2022-04-01/items?marketplaceIds=ATVPDKIKX0DER");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_USERAGENT, 'XXXXXXXXX-app/v1');
$response = curl_exec($curl);
```
The access token exists and has been retrieved from https://api.amazon.com/auth/o2/token#. What can be wrong? I was expecting our products list but getting the above error. |
For loop through the list unless empty? |
|python|for-loop|nonetype| |
My code keeps working for a couple inputs and then ends citing a segmentation fault. I do not do any dynamic memory allocation. It's supposed to be a game of reversi (aka othello). The include lab8part1 contains the stdbool and declares some of the functions.
```
#include <stdio.h>
#include <stdlib.h>
//#include "lab8part1.h"
#include <stdbool.h>
void printBoard(char board[][26], int n);
bool positionInBounds(int n, int row, int col);
bool checkLegalInDirection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol);
bool validMove(char board[][26], int n, int row, int col, char colour);
bool computerMove(char board[][26], int n, char colour, char row, char col);
bool UserMove(char board[][26], int n, char colour, char row, char col);
int checkBestMoves(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol);
bool checkifmove(char board[][26], int n, char color);
int
main(void)
{
char board[26][26],
color,
row,
col;
printf("Enter the board dimension: ");
int n;
scanf(" %d", &n);
int start = n / 2;
for (int m = 0; m < n; m++) {
for (int j = 0; j < n; j++) {
if ((m == start - 1 && j == start - 1) ||
(m == start && j == start)) {
board[m][j] = 'W';
}
else if ((m == start - 1 && j == start) ||
(m == start && j == start - 1)) {
board[m][j] = 'B';
}
else {
board[m][j] = 'U';
}
}
}
printf("Computer plays (B/W): ");
scanf(" %c", &color);
char color1;
if (color == 'B') {
color1 = 'W';
}
else {
color1 = 'B';
}
printBoard(board, n);
printf("\n");
char turn = 'B';
bool validmove = true;
while ((checkifmove(board, n, color) == true) ||
(checkifmove(board, n, color1) == true)) {
validmove = true;
if (turn == color) {
validmove = computerMove(board, n, color, row, col);
}
else {
UserMove(board, n, color1, row, col);
}
if (validmove == false) {
break;
}
if (turn == 'W') {
turn = 'B';
}
else {
turn = 'W';
}
}
int whitwin = 0;
int blacwin = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'W') {
whitwin += 1;
}
else {
blacwin += 1;
}
}
}
if (whitwin > blacwin) {
printf("W player wins.");
}
else if (whitwin < blacwin) {
printf("B player wins.");
}
else {
printf("Draw.");
}
return 0;
}
bool
computerMove(char board[][26], int n, char colour, char row, char col)
{
int movesrow[100] = { 0 };
int movescol[100] = { 0 };
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'U') {
if (checkLegalInDirection(board, n, i, j, colour, -1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
}
}
count += 1;
}
int bestMoves[600] = { 0 };
int tracker = 0;
int tot = 0;
for (int i = 0; i < count; i++) {
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
}
// if computer runs out of moves
if (bestMoves[0] == 0) {
printf("%c player has no valid move.", colour);
return false;
}
int counter = 0;
int bigNum = bestMoves[0];
int duplicates[tracker];
for (int i = 1; i < tracker; i++) {
if (bestMoves[i] > bigNum) {
bigNum = bestMoves[i];
duplicates[0] = i;
counter = 1;
}
else if (bestMoves[i] == bigNum) {
duplicates[counter] = i;
counter++;
}
}
int rowtemp = 0,
coltemp = 0;
for (int i = 0; i < counter; i++) {
for (int j = 0; j < n; j++) {
if ((movesrow[duplicates[i]] < movesrow[duplicates[i + j]]) &&
movescol[duplicates[i]] < movescol[duplicates[i + j]]) {
rowtemp = movesrow[duplicates[i]];
coltemp = movescol[duplicates[i]];
}
else {
rowtemp = movesrow[duplicates[i + j]];
coltemp = movescol[duplicates[i + j]];
}
}
}
row = rowtemp;
col = coltemp;
if (validMove(board, n, (row), (col), colour)) {
board[row][col] = colour;
printf("\nComputer places %c at %c%c\n", colour, (row + 'a'), (col + 'a'));
printBoard(board, n);
return true;
}
else {
return false;
}
}
bool
UserMove(char board[][26], int n, char colour, char row, char col)
{
int movesrow[100] = { 0 };
int movescol[100] = { 0 };
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'U') {
if (checkLegalInDirection(board, n, i, j, colour, -1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, -1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 0, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, -1)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 0)) {
movesrow[count] = i;
movescol[count] = j;
}
if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) {
movesrow[count] = i;
movescol[count] = j;
}
}
}
count += 1;
}
int bestMoves[100] = { 0 };
int tracker = 0;
int tot = 0;
for (int i = 0; i < count; i++) {
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
if (tot != 0) {
tracker += 1;
}
tot = 0;
for (int j = 0; j < count; j++) {
tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1);
if (tot != 0) {
bestMoves[tracker] = tot;
}
}
}
// if player runs out of moves
if (bestMoves[0] == 0) {
printf("%c player has no valid move.", colour);
return false;
}
printf("\nEnter a move for colour %c (RowCol): ", colour);
scanf(" %c%c", &row, &col);
if (validMove(board, n, (row - 'a'), (col - 'a'), colour)) {
board[row - 'a'][col - 'a'] = colour;
printBoard(board, n);
}
}
bool
validMove(char board[][26], int n, int row, int col, char colour)
{
int score = 0;
if (checkLegalInDirection(board, n, row, col, colour, -1, -1)) {
score++;
int i = 1;
while (board[row + (i * -1)][col + (i * -1)] != colour) {
board[row + (i * -1)][col + (i * -1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, -1, 0)) {
score++;
int i = 1;
while (board[row + (i * -1)][col + (i * 0)] != colour) {
board[row + (i * -1)][col + (i * 0)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, -1, 1)) {
score++;
int i = 1;
while (board[row + (i * -1)][col + (i * 1)] != colour) {
board[row + (i * -1)][col + (i * 1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 0, -1)) {
score++;
int i = 1;
while (board[row + (i * 0)][col + (i * -1)] != colour) {
board[row + (i * 0)][col + (i * -1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 0, 1)) {
score++;
int i = 1;
while (board[row + (i * 0)][col + (i * 1)] != colour) {
board[row + (i * 0)][col + (i * 1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 1, -1)) {
score++;
int i = 1;
while (board[row + (i * 1)][col + (i * -1)] != colour) {
board[row + (i * 1)][col + (i * -1)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 1, 0)) {
score++;
int i = 1;
while (board[row + (i * 1)][col + (i * 0)] != colour) {
board[row + (i * 1)][col + (i * 0)] = colour;
i++;
}
}
if (checkLegalInDirection(board, n, row, col, colour, 1, 1)) {
score++;
int i = 1;
while (board[row + (i * 1)][col + (i * 1)] != colour) {
board[row + (i * 1)][col + (i * 1)] = colour;
i++;
}
}
if (score > 0) {
return true;
}
else {
return false;
}
}
void
printBoard(char board[][26], int n)
{
printf(" ");
for (int i = 0; i < n; i++) {
printf("%c", 'a' + i);
}
for (int m = 0; m < n; m++) {
printf("\n%c ", 'a' + m);
for (int j = 0; j < n; j++) {
printf("%c", board[m][j]);
}
}
}
bool
positionInBounds(int n, int row, int col)
{
if (row >= 0 && row < n && col >= 0 && col < n) {
return true;
}
else {
return false;
}
}
bool
checkLegalInDirection(char board[][26], int n, int row, int col, char colour,
int deltaRow, int deltaCol)
{
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] != 'U') {
return false;
}
row += deltaRow;
col += deltaCol;
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] == colour || board[row][col] == 'U') {
return false;
}
while ((positionInBounds(n, row, col)) == true) {
if (board[row][col] == colour) {
return true;
}
if (board[row][col] == 'U') {
return false;
}
row += deltaRow;
col += deltaCol;
}
return false;
}
int
checkBestMoves(char board[][26], int n, int row, int col, char colour,
int deltaRow, int deltaCol)
{
int tiles = 0;
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] != 'U') {
return false;
}
row += deltaRow;
col += deltaCol;
if (positionInBounds(n, row, col) == false) {
return false;
}
if (board[row][col] == colour || board[row][col] == 'U') {
return false;
}
while ((positionInBounds(n, row, col)) == true) {
if (board[row][col] == colour) {
return tiles;
}
if (board[row][col] == 'U') {
return false;
}
tiles += 1;
row += deltaRow;
col += deltaCol;
}
return false;
}
bool
checkifmove(char board[][26], int n, char color)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'U') {
if (checkLegalInDirection(board, n, i, j, color, -1, -1) ||
checkLegalInDirection(board, n, i, j, color, -1, 0) ||
checkLegalInDirection(board, n, i, j, color, -1, 1) ||
checkLegalInDirection(board, n, i, j, color, 0, -1) ||
checkLegalInDirection(board, n, i, j, color, 0, 1) ||
checkLegalInDirection(board, n, i, j, color, 1, -1) ||
checkLegalInDirection(board, n, i, j, color, 1, 0) ||
checkLegalInDirection(board, n, i, j, color, 1, 1)) {
return true;
}
}
}
}
return false;
}
```
I have messed with shortening and expanding the array sizes but nothing seems to be working. I also tried using malloc but encountered the same problem. |
_Microsoft documentation:_
> [Range.Collapse method (Word)](https://learn.microsoft.com/en-us/office/vba/api/word.range.collapse?WT.mc_id=M365-MVP-33461&f1url=%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vbawd10.chm157155429)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue)
> [Selection.TypeText method (Word)](https://learn.microsoft.com/en-us/office/vba/api/word.selection.typetext?WT.mc_id=M365-MVP-33461&f1url=%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vbawd10.chm158663163)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue)
> [Selection object (Word)](https://learn.microsoft.com/en-us/office/vba/api/word.selection?WT.mc_id=M365-MVP-33461&f1url=%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vbawd10.chm2421)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue)
```vb
Set wdDoc = wdApp.Documents.Add
Const wdCollapseEnd = 0
With wdApp.Selection
.Font.Bold = True
.Typetext "Severity: "
.Collapse wdCollapseEnd
.Font.Bold = False
.Typetext Sheets("CleanSheet").Cells(2, 2).Value & vbCr
End With
```
|
I'm hacking the Linux kernel v5.15 and try to debug it with `gdb` line by line. I've opened the dwarf debug info through `make menuconfig`. However, it seems that some line will still be skipped. I find that the default compile optimization is -O2. So I changed the Makefile like:
```lang-make
ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE
KBUILD_CFLAGS += -O2 # here change to -O0
else ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE_O3
KBUILD_CFLAGS += -O3
else ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE
KBUILD_CFLAGS += -Os
endif
```
Then I compile again:
```lang-sh
make ARCH=riscv CROSS_COMPILE=riscv64-linux-gnu- -j$(nproc)
```
But it gives:
```lang-sh
CALL scripts/checksyscalls.sh
CALL scripts/atomic/check-atomics.sh
CC init/main.o
In file included from ././include/linux/compiler_types.h:85,
from <command-line>:
./arch/riscv/include/asm/jump_label.h: In function ‘want_init_on_alloc’:
./include/linux/compiler-gcc.h:88:38: warning: ‘asm’ operand 0 probably does not match constraints
88 | #define asm_volatile_goto(x...) do { asm goto(x); asm (""); } while (0)
| ^~~
./arch/riscv/include/asm/jump_label.h:20:9: note: in expansion of macro ‘asm_volatile_goto’
20 | asm_volatile_goto(
| ^~~~~~~~~~~~~~~~~
./include/linux/compiler-gcc.h:88:38: error: impossible constraint in ‘asm’
88 | #define asm_volatile_goto(x...) do { asm goto(x); asm (""); } while (0)
| ^~~
./arch/riscv/include/asm/jump_label.h:20:9: note: in expansion of macro ‘asm_volatile_goto’
20 | asm_volatile_goto(
| ^~~~~~~~~~~~~~~~~
./arch/riscv/include/asm/jump_label.h: In function ‘want_init_on_free’:
./include/linux/compiler-gcc.h:88:38: warning: ‘asm’ operand 0 probably does not match constraints
88 | #define asm_volatile_goto(x...) do { asm goto(x); asm (""); } while (0)
| ^~~
./arch/riscv/include/asm/jump_label.h:20:9: note: in expansion of macro ‘asm_volatile_goto’
20 | asm_volatile_goto(
| ^~~~~~~~~~~~~~~~~
make[1]: *** [scripts/Makefile.build:277: init/main.o] Error 1
make: *** [Makefile:1868: init] Error 2
```
If the optimization parameters really cannot be changed, is there a way to debug the kernel with finer granularity? |
> I had Win 10 systems and I was practicing on it and I always get
> addresses which are multiples of 2
>
> Know, I am practicing on Macbook Pro M3 and I get 9 digit addresses.
It does not depend on a number of digits only the the value of that number.
Example: `0x16fa13228` is `6167802408` in decimal. This number is dividable by 2. |
so I am new to Rust but recently came across a problem I don't know how to solve. It's to work with nested (and multi-dimensional) value-key pair arrays in Rust that is dynamically generated based on string splitting.
The sample dataset looks something like the example below:
Species | Category
Dog | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Canidae, Canis, C. familiaris
Cat | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Feliformia, Felidae, Felinae, Felis, F. catus
Bear | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Ursoidea, Ursidae, Ursus
...
The goal would be to split the comma delimitation and a create a map or vector. Essentially, creating "layers" of nested keys (either as a Vector array or a key to a *final value*).
From my understanding, Rust has a crate called "serde_json" which can be *used* to create key-value pairings like so:
let mut array = Map::new();
for (k, v) in data.into_iter() {
array.insert(k, Value::String(v));
}
As for comma delimited string splitting, it might look something like this:
let categories = "a, b, c, d, e, f".split(", ");
let category_data = categories.collect::<Vec<&str>>()
However, the end goal would be to create a recursively nested map or vector that follows the *Category* column for the array which can ultimately be serialised to a json output. How would this be implemented in Rust?
In addition, while we might know the number of rows in the sample dataset, isn't it quite resource intensive to calculate all the "comma-delimited layers" in the *Category* column to know the final size of the array as required by Rust's memory safe design to "initialize" an array by a defined or specified size? Would this need to specifically implemented as way to know the maximum number of layers in order to be doable? Or can we implement an infinitely nested multi-dimensional array without having to specify or initialise a defined map or vector size?
For further reference, in PHP, this might be implemented so:
$output_array = array();
foreach($data_rows as $data_row) {
$temp =& $output_array;
foreach(explode(', ', $data_row["Category"]) as $key) {
$temp =& $temp[$key];
}
// Check if array is already initialized, if not create new array with new data
if(!isset($temp)) {
$temp = array($data_row["Species"]);
} else {
array_push($temp, $data_row["Species"]);
}
}
How would a similar solution like this be implemented in Rust? Thanks in advance! |
I'm trying to solve a non-linear equation with nleqslv, and I know a priori if I want a positive or negative solution (it's a dataset on choice under risk, and I'm trying to compute the risk aversion coefficient for each individual under CRRA assumption. Since I can observe the DMs' choices, I already know if each DM is risk averse or not). Is there any way to enforce it?
I know I could try with different initial values; however, I'd like to find another way as I'm using nleqslv in a for loop (I must compute one solution for each observation) and I can't find an initial guess that works for everyone.
My code is the following:
`bernoulli <- function(x, r) {
ifelse(x>=0,((x+1)^(1-r)-1)/(1-r), -((-x+1)^(1-r)-1)/(1-r) )
}
bernoulli.log <- function(x) {
ifelse(x>=0, log(x+1), -log(-x+1) )}
mydata$alpha_crra <- NA
for (i in 1:nrow(mydata)) {
indiff.eq.crra <- function(r) {
return(bernoulli(mydata$CE[i], r) - mydata$p[i]*bernoulli(mydata$win[i], r)
- (1-mydata$p[i])*bernoulli(mydata$lose[i], r))
}
mydata$alpha_crra[i] <- ifelse(mydata$riskneutral[i] == 1, 0,
ifelse(abs(bernoulli.log(mydata$CE[i]) -
mydata$p[i]*bernoulli.log(mydata$win[i]) -
(1-mydata$p[i])*bernoulli.log(mydata$lose[i])) < 0.001 &
mydata$riskaverse[i] == 1, 1,
nleqslv(-5, indiff.eq.crra)$x))
}`
> where: mydata$win[i]= the high payoff of the lottery (can change depending on the observation)
> mydata$lose[i]= the low payoff of the lottery
> mydata$p[i] = probability to win the high payoff
> mydata$CE[i]= the Certainty Equivalent stated by DM i
> mydata$riskneutral[i] = a dummy variable = 1 if i is risk neutral, 0 otherwise
> mydata$riskaverse[i] = a dummy variable = 1 if i is risk averse, 0 otherwise
|
Since I ran into this problem AGAIN, and stumbled upon my previous question which helped me solve it, I figured I'd go ahead and post the solution to the problem so when I google it again next time I run into this problem it'll be here.
The `Content-Length` header is required. If you don't have it, you'll get an Unsupported Grant Type error message, which will leave you stumped and googling.
You're welcome, future self. |
I do homework for my lab on c++, I needed to get a number from keyboard and delete an element after inputted number in STL list. For some reason if I get 7 elements into the list, exactly {1,2,2,3,4,2,5} and ellement is 2 it outputs {1,2,2,2} and not {1,2,2,4,2}. Why?
```
#include <iostream>
#include <iterator>
#include <list>
using namespace std;
list<int> STL_MyList(std::list<int> g, int n);
int main()
{
int s, d;
list<int>::iterator it;
cout<<"Enter how many elements you want in the list?"<<endl;
cin>>s;
cout<<"Start now: "<<endl;
cin>>d;
list<int> list1{d};
for (int i = 0; i < s-1; ++i) {
cin>>d;
list1.push_back(d);
}
for (auto i : list1) {
cout << i << ' ';
}
cout<<endl<<"After what number do you want to delete element?"<<endl;
cin>>s;
list1.operator=(STL_MyList(list1, s));
cout<<"Result:"<<endl;
for (auto i : list1) {
cout << i << ' ';
}
cout<<endl<<"Do you want to do it again? (Yes - 1 / No - 0)"<<endl;
cin>>s;
if (s){
main();
} else{
cout<<"Finish.";
}
return 0;
}
//Delete element after n in STL list
list<int> STL_MyList(list<int> g, int n){
auto itr = g.begin();
int a=n-1;
for (itr = g.begin(); itr != g.end(); ++itr){
if (*itr!=n && a==n)
{
itr=g.erase(itr);
}
a=*itr;
}
return g;
}
```
I tried changing the code and logic behind it - but it all resulted in a lot of mistakes and whole code going south. |
Why my code is working on everything except one instance? |
|c++|list|function|stl| |
null |
After receiving Alex Mamo's response, I modified my code as follows:
**.update("guests.$guestId", guest)**
if (guest.toString().isNotEmpty()) {
// Get the guest_id from Guest model
val guestId = guest.toMap()["guest_id"]
// Update the document with the new data
dbCollectionEvents.document(eventId)
.update("guests.$guestId", guest)
.addOnSuccessListener {}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/kRHCB.png |
I am using fullcalendar v5 version and rendering the events with ```resourceTimeGrid```
After rendering my view is looking like this
[![enter image description here][1]][1]
When I tried to click on the date its not going to dayView. Even if I put console log the click event is not getting fired
I tried with following events but none of them is working,
First tried with dateClick
```
dateClick: function(info) {
alert('Clicked on: ' + info.dateStr);
alert('Coordinates: ' + info.jsEvent.pageX + ',' + info.jsEvent.pageY);
alert('Current view: ' + info.view.type);
// change the day's background color just for fun
info.dayEl.style.backgroundColor = 'red';
}
```
After that removed the date click and tried with ```navLinkDayClick```
```
navLinks: true,
navLinkDayClick: function(date, jsEvent) {
console.log('day', date.toISOString());
console.log('coords', jsEvent.pageX, jsEvent.pageY);
}
```
Both of them is not working.
I feel the above two events inside the calendar.
I am not able to find any events related to headerDateClick in full calendar v5
In fullcalendar V3, everything is working fine with adding any events and not sure why its not working in V5
[1]: https://i.stack.imgur.com/HMEhm.png |
I'm using Visual Studio 2022 Community, and C# projects. I like my namespaces to match my folder structures, so when I move a file from one folder to another within VS, I always accept the popup message offering to change the namespace too, or if I do the move outside of VS (e.g. in File Explorer), I go into the file within VS and open up the code fix stuff for the namespace. That always has an option to "Change namespace to match folder structure", which it says is associated with IDE0130.
That's all great, but I'd also like to get IDE0130 to automatically show up in the error list when I build the project, rather than needing to make sure I remember to use the code fix myself. Unfortunately, I have been unable to get it to show up there, ever.
I have added an ```.editorconfig``` file, and in it I enabled the rule as shown in [the docs for IDE0130](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0130):
```
dotnet_style_namespace_match_folder = true
```
That's the default anyway, but I figured might as well. I also set its severity to "warning", thinking that would cause it to show up in the error list, based on the same documentation page's example of how to set its severity to "none":
```
dotnet_diagnostic.IDE0130.severity = warning
```
It just never shows up in the error list. I have tried many things and done several experiments to try to figure out what's wrong, including but probably not limited to:
- Varying the location of ```.editorconfig``` (e.g. project level, solution level, ancestor of solution level).
- Putting these lines inside of the ```[*.cs]``` section or the ```[*.{cs,vb}]``` section... I don't care about VB, but the latter is what's shown on that documentation page, so I figured why not try it.
- Using the lines in combination or individually.
- Using the apparently old format of ```dotnet_style_namespace_match_folder = true:warning```
- Using severity "error" rather than "warning"
- Using or not using the project file ```CompilerVisibleProperty``` includes that are suggested on that page (this should not be necessary according to the page, as I'm compiling from within VS rather than from the command line, but hey)
- Unloading/reloading projects, closing/reopening solutions, stopping/restarting VS, building, rebuilding, cleaning build, etc.
- All of the above in various combinations and orders.
None of that helped.
I have verified that I can control another message in this way; for example IDE0290, "Use primary constructor":
```
dotnet_diagnostic.IDE0290.severity = error
```
When I add that line to the exact same ```.editorconfig``` file, instances of that diagnostic automatically change in the error list from their default "message" to "error".
I have also noticed that when I open up the code fix popup for an instance of IDE0130, I can select an option to set its severity there. Doing so automatically modifies (well, overwrites, actually ) the ```.editorconfig``` file seemingly with the exact same thing that I had/would put in there manually if I wanted the specified severity. And that still doesn't make IDE0130 show up.
Am I missing something here? Is there perhaps some other level of configuration that has to be set up in a certain way? Thanks for any help. |
Can't get IDE0130 to show up in VS2022 error list |
|c#|visual-studio|compiler-warnings|editorconfig| |
{"Voters":[{"Id":4621513,"DisplayName":"mkrieger1"},{"Id":235698,"DisplayName":"Mark Tolonen"},{"Id":6243352,"DisplayName":"ggorlen"}],"SiteSpecificCloseReasonIds":[13]} |
Upon trying to output the roles on page ListRoles.cshtml with the admin account in this project it gives me System.NullReferenceException: 'Object reference not set to an instance of an object.'...
I think the problem is in the processing of the request because when i add breakpoints on the lines that return the model to the view the model has it's roles.
Can anyone tell me how to fix it please!
have tried some things but nothing worked.
Here's the project: [https://github.com/bul-bbx/Rent_A_Car](https://github.com/bul-bbx/Rent_A_Car)
and here's the whole error:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCoreGeneratedDocument.Views_Role_Index.get_Model()
AspNetCoreGeneratedDocument.Views_Role_Index.ExecuteAsync() in Index.cshtml
@if (Model.Any())
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
here's the Index.cshtml file
@page
@using Rent_A_Car_v2.Areas.Identity.Data;
@model List<string>;
@{
ViewBag.Title = "List Role";
Layout = "~/Views/Role/_RoleLayout.cshtml";
}
<h1>Roles</h1>
<table class="table">
<thead>
<tr>
<th>Role Name</th>
</tr>
</thead>
<tbody>
@if (Model.Any())
{
foreach (var role in Model)
{
<tr>
<td>@role</td>
<td>
<a asp-action="EditRole" asp-route-roleName="@role">Edit</a> |
<a asp-action="DeleteRole" asp-route-roleName="@role">Delete</a>
</td>
</tr>
}
}
else
{
<tr>
<td>No roles available.</td>
</tr>
}
</tbody>
</table>
here's the RoleController.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.EntityFrameworkCore;
using Rent_A_Car_v2.Areas.Identity.Data;
namespace Rent_A_Car_v2.Controllers
{
public class RoleController : Controller
{
private readonly RoleManager<Role> roleManager;
private readonly UserManager<User> userManager;
private readonly AppDbContext DbContext;
public RoleController(UserManager<User> userManager, RoleManager<Role> roleManager, AppDbContext DbContext)
{
this.roleManager = roleManager;
this.userManager = userManager;
this.DbContext = DbContext;
}
[HttpGet]
public IActionResult AddUserToRole()
{
return View();
}
[HttpPost]
public async Task AddUserToRole(string u, string role)
{
User user = await userManager.FindByNameAsync(u);
await userManager.AddToRoleAsync(user, role);
}
[HttpPost]
public async Task AddUserToRole(User u, string role)
{
await userManager.AddToRoleAsync(u, role);
}
public IActionResult Index()
{
var roles = roleManager.Roles;
var a = roles.Select(role => role.Name).ToList();
return View(a);
}
[HttpGet]
public IActionResult CreateRole()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreateRole(Role model)
{
if (ModelState.IsValid)
{
Role Role = new Role
{
Name = model.Name
};
IdentityResult result = await roleManager.CreateAsync(Role);
if (result.Succeeded)
{
RedirectToAction("ListRole", "Role");
}
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View(model);
}
[HttpGet]
public async Task<IActionResult> EditRole(string roleId)
{
// Retrieve the role from the database
var role = await roleManager.FindByNameAsync(roleId);
if (role == null)
{
return NotFound(); // Or handle the error as needed
}
// Pass the role to the view for editing
return View(role);
}
// POST: /Role/EditRole/roleId
[HttpPost]
public async Task<IActionResult> EditRole(string roleId, Role updatedRole)
{
if (roleId != updatedRole.Name)
{
return BadRequest();
}
// Retrieve the role from the database
var role = await roleManager.FindByNameAsync(roleId);
if (role == null)
{
return NotFound(); // Or handle the error as needed
}
// Update role details
role.Name = updatedRole.Name; // Update other properties as needed
// Update the role in the database
var result = await roleManager.UpdateAsync(role);
if (result.Succeeded)
{
// Role updated successfully
return RedirectToAction("Index", "Home"); // Redirect to a relevant page
}
else
{
// Failed to update role, handle the error
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(updatedRole); // Return to the edit form with error messages
}
}
//[HttpGet]
//public IActionResult DeleteRole()
//{
// return View();
//}
//[HttpPost]
//public async Task<IActionResult> DeleteRole(DeleteRoleViewModel model)
//{
// var role = await roleManager.FindByNameAsync(model.ExistingRoleName);
// if (role == null)
// {
// return NotFound();
// }
// var result = await roleManager.DeleteAsync(role);
// if (result.Succeeded)
// {
// return RedirectToAction("ListRole", "Role");
// }
// else
// {
// foreach (var error in result.Errors)
// {
// ModelState.AddModelError(string.Empty, error.Description);
// }
// return View("Error");
// }
//}
}
}
|
Background: Currently trying to implement a feature so that users on my site can upload their profile image to GCS.
I understand that there are two ways you could upload objects when using the client library:
The standard way (see here: https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-nodejs) and 2. doing it with a Signed URL (see here: https://cloud.google.com/storage/docs/samples/storage-generate-upload-signed-url-v4)
Just wondering which way would be better for my particular use case? |
Best way to upload images to Google Cloud Storage? |
|node.js|google-cloud-platform|next.js| |
{"Voters":[{"Id":1563833,"DisplayName":"Wyck"}]} |
It's because in `GetAllProducts`, type `T` is not decided yet. So it is impossible to assign `[]models.Products` to `T`.
```golang
func (db *DbConnection[T]) GetAllProducts() {
var re []models.Products
re, _ = db.GetAll()
}
```
But you can assign `models.Products` to `T` if `T` is decided as `models.Products`, like this.
```golang
db := DbConnection[models.Products]{}
var re []models.Products
re, _ = db.GetAll()
```
I reproduce your problem in the simplified version(https://go.dev/play/p/GHkDThFLOKG). You can find the same error `GetAllProducts()` but in the main code, it works. |
I have a multi-threaded implementation of Mandelbrot. Instead of scanning X and Y in nested loops, I scan pixels from 0 to width*height. The Mandelbrot worker thread then calculates the logical and real coordinates of the pixel. Here is a subset of the code...
```
// Worker thread for processing the Mandelbrot algorithm
DWORD WINAPI MandelbrotWorkerThread(LPVOID lpParam)
{
// This is a copy of the structure from the paint procedure.
// The address of this structure is passed with lParam.
typedef struct ThreadProcParameters
{
int StartPixel;
int EndPixel;
int yMaxPixel;
int xMaxPixel;
uint32_t* BitmapData;
double dxMin;
double dxMax;
double dyMin;
double dyMax;
} THREADPROCPARAMETERS, *PTHREADPROCPARAMETERS;
PTHREADPROCPARAMETERS P;
P = (PTHREADPROCPARAMETERS)lpParam;
// Algorithm obtained from https://en.wikipedia.org/wiki/Mandelbrot_set.
double x0, y0, x, y, xtemp;
int iteration;
// Loop for each pixel in the slice.
for (int Pixel = P->StartPixel; Pixel < P->EndPixel; ++Pixel)
{
// Calculate the x and y coordinates of the pixel.
int xPixel = Pixel % P->xMaxPixel;
int yPixel = Pixel / P->xMaxPixel;
// Calculate the real and imaginary coordinates of the point.
x0 = (P->dxMax - P->dxMin) / P->xMaxPixel * xPixel + P->dxMin;
y0 = (P->dyMax - P->dyMin) / P->yMaxPixel * yPixel + P->dyMin;
// Initial values.
x = 0.0;
y = 0.0;
iteration = 0;
// Main Mandelbrot algorithm. Determine the number of iterations
// that it takes each point to escape the distance of 2. The black
// areas of the image represent the points that never escape. This
// algorithm is supposed to be using complex arithmetic, but this
// is a simplified separation of the real and imaginary parts of
// the point's coordinate. This algorithm is described as the
// naive "escape time algorithm" in the WikiPedia article noted.
while (x * x + y * y <= 2.0 * 2.0 && iteration < max_iterations)
{
xtemp = x * x - y * y + x0;
y = 2 * x * y + y0;
x = xtemp;
++iteration;
}
// When we get here, we have a pixel and an iteration count.
// Lookup the color in the spectrum of all colors and set the
// pixel to that color. Note that we are only ever using 1000
// of the 16777215 possible colors. Changing max_iterations uses
// a different pallette, but 1000 seems to be the best choice.
// Note also that this bitmap is shared by all 64 threads, but
// there is no concurrency conflict as each thread is assigned
// a different region of the bitmap. The user has the option of
// using the original RGB or the new and improved Log HSV system.
if (!bUseHSV)
{
// The old RGB system.
P->BitmapData[Pixel] = ReverseRGBBytes
((COLORREF)(-16777215.0 / max_iterations * iteration + 16777215.0));
}
else
{
// The new HSV system.
sRGB rgb;
sHSV hsv;
hsv = mandelbrotHSV(iteration, max_iterations);
rgb = hsv2rgb(hsv);
P->BitmapData[Pixel] =
(((int)(rgb.r * 255))) +
(((int)(rgb.g * 255)) << 8) +
(((int)(rgb.b * 255)) << 16 );
}
}
// End of thread execution. The return value is available
// to the invoking thread, but we don't presently use it.
return 0;
```
This can be broken up into as many threads as desired. My program, for instance, allows between 1 and 64 threads. For the full program, see https://github.com/alexsokolek2/mandelbrot. Good luck. |
I have implemented LCA of a binary tree problem on Leetcode using Python: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
But I got error: TypeError: list indices must be integers or slices, not TreeNode. I am wondering how do I keep track of all parents treenode in self.up 2d array in Python.
`
from collections import defaultdict
import math
class Solution:
def __init__(self):
# self.tin=defaultdict(int)
# self.tout=defaultdict(int)
self.level=[0 for i in range(10**5+1)]
self.logN=math.ceil(math.log(10**5))
self.up=[[TreeNode(-1) for i in range(self.logN + 1)] for j in range(10**5 + 1)]
def dfs(self, root, parent):
# self.tin[root.val]+=1
self.up[root][0]=parent
for i in range(1, self.logN+1):
up[root][i]=up[ up[root][i-1] ][i-1]
if root.left:
self.level[root.left]=self.level[root]+1
dfs(self, root.left, root)
if root.right:
self.level[root.right]=self.level[root]+1
dfs(self, root.right, root)
self.tout[root]+=1
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.dfs(root,root)
def is_ancestor(n1, n2):
return self.tin[n1]<=self.tin[n2] and self.tout[n1]>=self.tout[n2]
def lca(n1, n2):
if self.level[n1]<self.level[n2]:
return lca(n2,n1)
if is_ancestor(n1, n2):
return n1
if is_ancestor(n1, n2):
return n2
for i in range(self.logN, -1, -1):
if is_ancestor(self.up[n1][i], n2)==False:
n1=self.up[n1][i]
return self.up[n1][0]
return lca(p, q)`
This is how I initialized up array to track all the upper level nodes of a current node:
self.up=[[-1 for i in range(self.logN + 1)] for j in range(10**5 + 1)]
and then I tried to change it to:
self.up=[[TreeNode(-1) for i in range(self.logN + 1)] for j in range(10**5 + 1)]
But apparently, both of them gave me the same error:
TypeError: list indices must be integers or slices, not TreeNode.
Can someone please help!!thank you!!! |
null |
I think this is pretty good:
```
db['date'] = db['date'] + pd.to_timedelta(7-db['date'].dt.dayofweek,'d')
``` |
**TL;DR** In version 2.4-0 of `exams` (current CRAN version at the time of writing) there is no way of accomplishing this. In version 2.4-1 (current development version on R-Forge) we have started working towards an `exams2inspera()` interface that might get you a few steps further. To try it out install:
install.packages("exams", type = "source", repos = "https://R-Forge.R-project.org")
**Details:** Following a [discussion on Inspera in our R-Forge forum](https://R-Forge.R-project.org/forum/forum.php?thread_id=34379&forum_id=4377&group_id=1337) we have added a new `exams2inspera()` interface to the package that calls `exams2qti21()` with (a) an adapted XML template, (b) using MathML (rather than MathJax) for mathematical notation, (c) supplements embedded without Base64. Additionally, I have just added (d) the `expectedLength` option for numeric exercises. After installing the development option you can try
exams2inspera(...)
exams2qti21(..., flavor = "inspera")
The first command employs changes (a)-(d), the second one only (d).
**Next steps:** I would expect that further problems come up or that further tweaks are needed to make everything work as intended in Inspera. And I cannot test things out myself because I haven't got access to Inspera. Hence, StackOverflow is not the right platform to track these problems. If needed, I suggest that you open up a new discussion in the R-Forge forum. |
You have to change the docker **entrypoint** command like below to use a custom `vault.hcl` file.
vault server -config=/vault/vault.hcl
Example `docker-compose.yaml` file (vault.hcl file resides inside `/home/volumes/vault/`)
version: "3.8"
services:
vault:
image: hashicorp/vault
container_name: vault
environment:
VAULT_ADDR: http://127.0.0.1:8200
ports:
- "8200:8200"
volumes:
- /home/volumes/vault/:/vault/:rw
cap_add:
- IPC_LOCK
entrypoint: vault server -config=/vault/vault.hcl |
{"Voters":[{"Id":87698,"DisplayName":"Heinzi","BindingReason":{"GoldTagBadge":"c#"}}]} |
How can I use unified memory on an OpenCL device without copying data correctly?
OpenCL defined [CL_DEVICE_HOST_UNIFIED_MEMORY](https://registry.khronos.org/OpenCL/sdk/3.0/docs/man/html/clGetDeviceInfo.html ) as:
> Is CL_TRUE if the device and the host have a unified memory subsystem and is CL_FALSE otherwise.
The ARM Mali [docs]( https://developer.arm.com/documentation/101574/0400/Optimizing-OpenCL-for-Mali-GPUs/Optimizing-memory-allocation/About-memory-allocation?lang=en) suggests to use unified memory, the flag `CL_MEM_ALLOC_HOST_PTR` should be used while creating a buffer. The flag is described as:
> This is a hint to the driver indicating that the buffer is accessed on the host side. To use the buffer on the application processor side, you must map this buffer and write the data into it. This is the only method that does not involve copying data. If you must fill in an image that is processed by the GPU, this is the best way to avoid a copy.
However, there are no examples of how to use buffers created with the flag `CL_MEM_ALLOC_HOST_PTR`. The example I wrote does not seem to do it properly.
Consider the following code snippet to use such buffers:
```c++
// Create Buffers
constexpr size_t n_bytes = sizeof(int) * SZ_ARR;
cl::Buffer buffer_A(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
n_bytes);
cl_int error{0};
int* A = static_cast<int*>(
queue.enqueueMapBuffer(buffer_A, CL_FALSE, CL_MAP_WRITE, 0, n_bytes,
nullptr, nullptr, &error));
gpuErrchk(error);
for (size_t i = 0; i < SZ_ARR; ++i) {
A[i] = i;
}
gpuErrchk(queue.enqueueUnmapMemObject(buffer_A, A));
cl::Kernel add(program, "add_and_print");
add.setArg(0, buffer_A);
gpuErrchk(queue.enqueueNDRangeKernel(add, cl::NullRange,
cl::NDRange(SZ_ARR), cl::NullRange));
queue.finish();
```
I am creating the buffer `buffer_A` to contain ten ints. I expect to write these ten ints after mapping them with `enqueueMapBuffer` and then unmapping them with `enqueueUnmapMemObject`. The kernel `add_and_print` adds `1` to each array element and prints the resulting value. In particular, the kernel is:
```c++
const std::string kernel_code =
" void kernel add_and_print(global int* A) {"
" int i = get_global_id(0);"
" A[i] = A[i] + 1;"
" printf(\"%d\", A[i]);"
" }";
```
However, the program prints `1` for each array element.
How can I use a unified buffer properly?
For reference, the full program to reproduce the code is below:
```c++
#include <CL/opencl.hpp>
#include <iostream>
#define gpuErrchk(ans) \
{ gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cl_int code, const char* file, int line,
bool abort = true) {
if (code != CL_SUCCESS) {
fprintf(stderr, "GPUassert, error code: %d %s %d\n", code, file, line);
if (abort) exit(code);
}
}
constexpr size_t SZ_ARR = 10;
cl::Device getDevice() {
std::vector<cl::Platform> all_platforms;
gpuErrchk(cl::Platform::get(&all_platforms));
cl::Platform default_platform = all_platforms[0];
std::vector<cl::Device> all_devices;
gpuErrchk(default_platform.getDevices(CL_DEVICE_TYPE_GPU, &all_devices));
cl::Device default_device = all_devices[0];
std::cout << "Using device: " << default_device.getInfo<CL_DEVICE_NAME>()
<< "\n";
return default_device;
}
cl::Program buildProgram(cl::Context& context, cl::Device& device) {
const std::string kernel_code =
" void kernel add_and_print(global int* A) {"
" int i = get_global_id(0);"
" A[i] = A[i] + 1;"
" printf(\"%d\", A[i]);"
" }";
cl::Program::Sources sources{{kernel_code.c_str(), kernel_code.length()}};
cl::Program program(context, sources);
if (program.build({device}) != CL_SUCCESS) {
std::cout << "Error building: "
<< program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device)
<< std::endl;
exit(1);
}
return program;
}
int main() {
// Prologue: Get device, context, and build program
cl::Device default_device = getDevice();
cl::Context context({default_device});
cl::Program program = buildProgram(context, default_device);
cl::CommandQueue queue(context, default_device);
// Create Buffers
constexpr size_t n_bytes = sizeof(int) * SZ_ARR;
cl::Buffer buffer_A(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
n_bytes);
cl_int error{0};
int* A = static_cast<int*>(
queue.enqueueMapBuffer(buffer_A, CL_FALSE, CL_MAP_WRITE, 0, n_bytes,
nullptr, nullptr, &error));
gpuErrchk(error);
for (size_t i = 0; i < SZ_ARR; ++i) {
A[i] = i;
}
gpuErrchk(queue.enqueueUnmapMemObject(buffer_A, A));
cl::Kernel add(program, "add_and_print");
add.setArg(0, buffer_A);
gpuErrchk(queue.enqueueNDRangeKernel(add, cl::NullRange,
cl::NDRange(SZ_ARR), cl::NullRange));
queue.finish();
}
``` |
How to exploit Unified Memory in OpenCL with CL_MEM_ALLOC_HOST_PTR flag? |
|arm|opencl|mali|unified-memory| |
I am trying to program a COM object with the Enumerable and Enumerator inside in Delphi. It's a nightmare.
First in the .ridl file:
[![enter image description here][1]][1]
next in the _tlb.pas I have this:
// *********************************************************************//
// Interface : ITrackingRatesCol
// Indicateurs : (4416) Dual OleAutomation Dispatchable
// GUID : {F116E1DA-7E3E-4207-BD17-1615DCE4BE41}
// *********************************************************************//
ITrackingRatesCol = interface(IEnumerable)
['{F116E1DA-7E3E-4207-BD17-1615DCE4BE41}']
function Get_Count: Integer; safecall;
property Count: Integer read Get_Count;
end;
// *********************************************************************//
// DispIntf : ITrackingRatesColDisp
// Indicateurs : (4416) Dual OleAutomation Dispatchable
// GUID : {F116E1DA-7E3E-4207-BD17-1615DCE4BE41}
// *********************************************************************//
ITrackingRatesColDisp = dispinterface
['{F116E1DA-7E3E-4207-BD17-1615DCE4BE41}']
property Count: Integer readonly dispid 1;
function GetEnumerator: IEnumVARIANT; dispid -4;
end;
And in my .pas file of my object:
TTrackingRatesCol = class(TAutoObject, ITrackingRatesCol,IEnumerable)
private
fIndex,fCount:integer;
protected
function GetCurrent:driverates;safecall;
function Get_Count: Integer; safecall;
function MoveNext: WordBool; safecall;
function GetEnumerator: IEnumerator; safecall;
public
procedure Initialize; override;
destructor Destroy; override;
end;
implementation
uses ComServ,Data.Win.ADODB,Core,SysUtils;
function TTrackingRatesCol.GetEnumerator: IEnumerator;
begin
result:=self;
end;
But I have allways the message: that the implementation of the interface IEnumerable.GetEnumerator is missing!!
Thanks a lot for your help.
Michel
[1]: https://i.stack.imgur.com/RPaEQ.png
|
|python|turtle-graphics|python-turtle| |
You are doing it very bad. `php artisan serve` is a [server for local development, not for production][1].
I will asume that you have nginx installed, and that you already configured .env file, databases and all other things for production. If not, please follow [this tutorial][2]
First of all, you need to copy (or link) your project directory to /var/www
- `# cp /path/toyour/project-directory /var/www/yourproject -r`. This command will copy your project. Also you can use `mv` for move or `ln -s` for link.
- `# vim /etc/nginx/sites-available/yourproject`
```server {
listen 80;
server_name server_domain_or_IP;
root /var/www/yourproject/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
# Please change your PHP version based on your setup.
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
} # Dont forget save it.```
- `# ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled/yourproject`
With `# nginx -t` you can test your configuration. If is ok, you can reload service with `# nginx -s reload`
Notes
- Set your own PHP version
- Set your own domain name
- `#` in the commands, indicates that you need do it as root.
After this configuration, you need set up the permissions:
- `# chown -R www-data:www-data /var/www/yourproject/storage`
- `# chown -R www-data:www-data /var/www/yourproject/bootstrap/cache`
[1]: https://stackoverflow.com/questions/34978857/laravel-how-to-start-server-in-production
[2]: https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-laravel-with-nginx-on-ubuntu-20-04 |
datetime...
```SQL
SELECT days= CONVERT(int,cast('02-02-2024' as datetime)), dt = convert(date, (convert(datetime, 45322)))
```
result would be
|days|dt|
|---|---|
|45322|2024-02-02|
|
Here's a list of resources to get started with the Python debugger:
1. Read Steve Ferb's article ["Debugging in Python"][ferg]
2. Watch Eric Holscher's screencast ["Using pdb, the Python Debugger"][holscher]
3. Read the [Python documentation for pdb — The Python Debugger][pydoc]
4. Read Chapter 9—When You Don't Even Know What to Log: Using Debuggers—of Karen Tracey's [*Django 1.1 Testing and Debugging*][tracey].
[tracey]: https://www.packtpub.com/django-1-1-testing-and-debugging/book
[pydoc]: http://docs.python.org/library/pdb.html
[ferg]: https://web.archive.org/web/20110718104449/http://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/
[ayman]: https://gimmebar-assets.s3.amazonaws.com/4fe38b76be0a5.html
[holscher]: http://ericholscher.com/blog/2008/aug/30/using-pdb-python-debugger-django-debugging-series-/ |
Disabling the `mitm_http2` flag within `seleniumwire_options`, as recommended by the seleniumwire author for similar issues, did not work for me:
seleniumwire_options = {
'mitm_http2': False,
}
I include it here as other users have reported success with this for other sites.
Disabling HTTP2 in my chromedriver instance is the workaround I settled for:
chrome_options.add_argument('--disable-http2')
|
You should sort the list of integers in descending order and then iterate through it, adding each number to the list with the smaller current sum, like the following:
```python
import random
intList = []
for i in range(10):
intList.append(random.randint(10, 200))
listX = []
listY = []
intList.sort(reverse=True)
sumX = 0
sumY = 0
for num in intList:
if sumX <= sumY:
listX.append(num)
sumX += num
else:
listY.append(num)
sumY += num
print(f"listx = {listX} \nlisty = {listY}\n sum x = {sumX}, y = {sumY}")
``` |
|gcc|x86|inline-assembly| |
you need to define second argument "tree" as empty
Here is example: `istree(t(a, t(b, nil, nil), empty)).`
domains
tree = nil; t(symbol, tree, tree); empty().
predicates
istree(tree).
clauses
istree(nil).
istree(t(_, L, R)) :- istree(L), istree(R).
goal
istree(t(a, t(b, nil, nil), empty)). |
I'm pretty sure that Google used to publish an XML snippet of how to add a banner AdView to the layout, a ConstraintLayout to be precise. But that isn't in the [documentation](https://developers.google.com/admob/android/banner) anymore.
There is a section called **Add AdView to the layout** and it contains a code snipped with some weird screen size calculations without any explanations of why I have to do this. I haven't seen this before. Is this supposed to integrate with *Compose* somehow? If so, how?
However, I'm on a good old XML layout. How to integrate an AdView in an XML layout in 2024? |
How to add a banner adview to the layout? |
|android|admob|google-play-services| |
How can I remove Textfield focus when I press return or click outside Textfield?
Note that this is SwiftUI on macOS.
If I do this:
```swift
import SwiftUI
struct ContentView: View {
@State var field1: String = "This is the Text Field View"
var body: some View {
VStack{
Button("Press") {
print("Button Pressed")
}
TextField("Fill in Text", text: Binding(
get: { print("get") ; return self.field1 },
set: { print("set") ; self.field1 = $0 }
)
)
}
}
}
```
then click into the TextField and edit it then click on the Button the TextField does not lose focus. How can I make it exit editing mode and lose focus?
I would also like to lose focus from the TextField if I press Return.
I used the Binding initialiser with get and set because I thought I could somehow intercept keypresses and detect the 'Return' character but this doesn't work.
|
Im facing this error Your requirements could not be resolved to an installable set of packages when trying to run composer update |
|php| |
null |
I recently upgraded my Angular project to version 17, and now I'm encountering many browser console warnings like the following messages.
`NG0912: Component ID generation collision detected. Components 'DevDashboardComponent' and 'DevDashboardComponent' with selector 'lib-dev-dashboard-page' generated the same component ID. To fix this, you can change the selector of one of those components or add an extra host attribute to force a different ID. Find more at https://angular.io/errors/NG0912`
`NG0912: Component ID generation collision detected. Components 'ScrollerComponent' and 'ScrollerComponent' with selector 'datatable-scroller' generated the same component ID. To fix this, you can change the selector of one of those components or add an extra host attribute to force a different ID. Find more at https://angular.io/errors/NG0912`
Despite having different selector IDs for each library in my Angular project, these warnings persist. These warnings didn't appear before the upgrade.
However, after building the project using *ng build* and running it, the warnings doesn't appear.
Is there any specific configuration or setting that needs to be adjusted after upgrading to angular 17 to prevent this warning?
Any insights or suggestions would be appreciated. |
Angular NG0912 Warning: Component ID generation collision detected after upgrading to angular 17 |
|angular|warnings|angular17|browser-console|versionupgrade| |
null |
I am currently working on a .NET project where I am utilizing Entity Framework. I require assistance with sorting users by date. Specifically, I need to sort users based on multiple dates. In the user entity, there are createDate and updateDate fields. Additionally, each user contains a list of items, each of which also possesses createDate and updateDate attributes.
My objective is to sort users by the latest user date or user items last update or create date among the following: user.createDate, user.updateDate, item.createDate, and item.updateDate.
But if I update user item and the item will have updated date I also need to prefer this user with updated item. This mean if the user item date is newer then other user create or update date, the user with updated item will be preferred.
```csharp
public class User
{
public Guid Id { get; set; }
public string FirstName { get; set; };
public string LastName { get; set; };
public string Email { get; set; };
public virtual ICollection<Item> Items { get; set; };
public Datetime CreatedDate { get; set; }
public Datetime? UpdatedDate { get; set; }
}
```
```csharp
public class Item
{
public Guid Id { get; set; }
public string Name { get; set; };
public Datetime CreatedDate { get; set; }
public Datetime? UpdatedDate { get; set; }
}
```
I tried for example this, where i try to use ordering by multiple columns, but in this situation the user with updated item is not preferred.
```csharp
users = users
.OrderByDescending(u => u.UpdatedAt ?? u.CreatedAt)
.ThenByDescending(u => u.Items.Any() ? u.Items.Max(i => i.UpdatedAt ?? i.CreatedAt) : DateTime.MinValue)
```
Could you please advise on how I can achieve this sorting only with working with IQueryable? Is this feasible?
I need to implement function that take reference to iqueryable<User> end sort the users
```chsarp
private static void UserSortByActivity(ref IQueryable<User> users)
{
}
```
Example of data:
```csharp
List<User> users = new List<User>
{
new User
{
Id = Guid.NewGuid(),
FirstName = "John",
LastName = "Doe",
createdDate = "2021-01-01",
UpdatedDate = null,
Items = new List<Item>
{
new Item
{
Id = Guid.NewGuid(),
Name = "Item1",
CreatedDate = "2021-01-01",
UpdatedDate = "2021-01-02",
},
new Item
{
Id = Guid.NewGuid(),
Name = "Item2",
CreatedDate = "2021-01-01",
UpdatedDate = "2021-01-03",
},
}
},
new User
{
Id = Guid.NewGuid(),
FirstName = "Jane",
LastName = "Doe",
createdDate = "2021-02-01",
UpdatedDate = "2021-02-02",
Items = new List<Item>
{
new Item
{
Id = Guid.NewGuid(),
Name = "Item3",
CreatedDate = "2021-02-01",
UpdatedDate = "2021-02-02",
},
new Item
{
Id = Guid.NewGuid(),
Name = "Item4",
CreatedDate = "2021-02-01",
UpdatedDate = "2021-06-03",
},
}
},
new User
{
Id = Guid.NewGuid(),
FirstName = "Alice",
LastName = "Smith",
createdDate = "2021-03-01",
UpdatedDate = "2021-03-02",
Items = new List<Item>();
},
};
```
Possible sorted output
First: Jane Doe (last updated item on 2021-06-03)
Second: Alice Smith (last user updated on 2021-03-02)
Third: John Doe (last updated item on 2021-01-03)
|
LCA of a binary tree implemented in Python |
|python|algorithm|lowest-common-ancestor| |
null |
I want to use JCA(Java connector architecture) and get data from Mainframe system using IBM provided Resource adapter(.rar) file. I could not find out this file in IBM portal. Since it is an old way of connecting from Java to Mainframe, it may not available. Please help me to find out.
I'm looking for IBM provided ECI resource adapter (cicseci.rar) file. This file to be deployed in WAS server along with my client side code to establish the connection between Java and IBM mainframe system |
Where can I download ECI resource adapter (cicseci.rar). Unable to find out it in IBM portal |
|java|websphere-liberty|mainframe|rar|jca| |
null |
Your container's ID contains a space but they're illegal.
<div id="Sign-In TempUI"
Get rid of it. Also...
document.addEventListener('DOMContentLoaded',
Why are you in such a hurry? Use LOAD...
document.addEventListener('load',
The only time one would need to listen to *DOMContentLoaded* is if they’re writing a utility that does performance timing on pages!
|
If you want to extend an idea/discussion please post a reply to the same thread instead of posting a new Discussion. |
null |
I have implemented LCA of a binary tree problem on Leetcode using Python: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
But I got error: TypeError: list indices must be integers or slices, not TreeNode. I am wondering how do I keep track of all parents treenode in self.up 2d array in Python.
from collections import defaultdict
import math
class Solution:
def __init__(self):
# self.tin=defaultdict(int)
# self.tout=defaultdict(int)
self.level=[0 for i in range(10**5+1)]
self.logN=math.ceil(math.log(10**5))
self.up=[[TreeNode(-1) for i in range(self.logN + 1)] for j in range(10**5 + 1)]
def dfs(self, root, parent):
# self.tin[root.val]+=1
self.up[root][0]=parent
for i in range(1, self.logN+1):
up[root][i]=up[ up[root][i-1] ][i-1]
if root.left:
self.level[root.left]=self.level[root]+1
dfs(self, root.left, root)
if root.right:
self.level[root.right]=self.level[root]+1
dfs(self, root.right, root)
self.tout[root]+=1
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.dfs(root,root)
def is_ancestor(n1, n2):
return self.tin[n1]<=self.tin[n2] and self.tout[n1]>=self.tout[n2]
def lca(n1, n2):
if self.level[n1]<self.level[n2]:
return lca(n2,n1)
if is_ancestor(n1, n2):
return n1
if is_ancestor(n1, n2):
return n2
for i in range(self.logN, -1, -1):
if is_ancestor(self.up[n1][i], n2)==False:
n1=self.up[n1][i]
return self.up[n1][0]
return lca(p, q)
This is how I initialized up array to track all the upper level nodes of a current node:
self.up=[[-1 for i in range(self.logN + 1)] for j in range(10**5 + 1)]
and then I tried to change it to:
self.up=[[TreeNode(-1) for i in range(self.logN + 1)] for j in range(10**5 + 1)]
But apparently, both of them gave me the same error:
TypeError: list indices must be integers or slices, not TreeNode.
Can someone please help!!thank you!!!
|
There was also a proposal to add a "Sentinel" class to the Python standard library:
https://peps.python.org/pep-0661/
That points you to a GitHub repo containing a reference implementation:
https://github.com/taleinat/python-stdlib-sentinels
It has a license allowing incorporation in any project. |
this is a problem I am facing. When trying to composite several bitmaps together I get a weird result.
[Desired result (but this was done manually)][1]
[Current result with the weird oddities][2]
[1]: https://i.stack.imgur.com/Xa5hv.png
[2]: https://i.stack.imgur.com/Ukhl6.png
This is the code snippet. Here I am trying to use two byte arrays each containing ARGB values.
```csharp
public static void Composite(this byte[] input, byte[] layer, int x, int y, int width, int height)
{
int w = width;
if (w > RewBatch.width)
{
w = RewBatch.width;
}
Parallel.For(0, height, j =>
{
for (int i = 0; i < w; i += 4)
{
int whoAmI = (y + j) * w + (x + i);
if (whoAmI < 0 || whoAmI > input.Length)
{
continue;
}
Pixel _one = Pixel.Extract32bit(input, whoAmI);
Pixel _two = Pixel.Extract32bit(layer, j * width + i);
if (_two.A < 255)
{
Color blend = _two.color.Blend(_one.color, 0.15d);
input[whoAmI] = blend.B;
input[whoAmI + 1] = blend.G;
input[whoAmI + 2] = blend.R;
input[whoAmI + 3] = blend.A;
}
else
{
input[whoAmI] = 255;
input[whoAmI + 1] = _two.color.R;
input[whoAmI + 2] = _two.color.G;
input[whoAmI + 3] = _two.color.B;
}
}
});
}
``` |
Compositing ARGB Bitmaps Together CPU-only |
|c#|arrays|real-time|alphablending|compositing| |
You can possibly use
networkx's Edmond's algorithm to find minimum spanning arborescence rooted at a particular root in a given directed graph.
https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.tree.branchings.Edmonds.html
In graph theory, an arborescence is a directed graph having a distinguished vertex u (called the root) such that, for any other vertex v, there is exactly one directed path from u to v.
In graph theory, Edmonds' algorithm or Chu–Liu/Edmonds' algorithm is an algorithm for finding a spanning arborescence of minimum weight (sometimes called an optimum branching). It is the directed analog of the minimum spanning tree problem. |
You can use PHP's `nl2br()` function to convert newline characters to `<br>` tags. This will preserve the line breaks when displaying the text in HTML. However, it would be best if you also used `strip_tags()` to remove the `<p>` tags before converting newline characters to `<br>` tags.
{!! Form::textarea('mline', isset($mline) ? nl2br(strip_tags($mline)) : null, ['style'=>'height: 113px;width:150%;','class'=>'p-2']) !!} |
In Rust, I'm able to downcast a trait object to a concrete type using .as_any().downcast_ref(). That works ok, but it returns a &ref, not the owned object itself.
How can I get ownership of a downcast object? |
{"Voters":[{"Id":215552,"DisplayName":"Heretic Monkey"},{"Id":3959259,"DisplayName":"Bill Tür stands with Ukraine"},{"Id":1159478,"DisplayName":"Servy"}]} |
I have 2 tables of data. 1 table has a list of start and end date ranges. The other table a list of students with their class and start dates. For each of the date ranges, I'm trying to list the students who have a start date in that range.
Range Data
| Start | End |
| ---------- | ----------- |
| 10/1/2023 | 12/31/2023 |
| 7/1/2023 | 9/30/2023 |
| 4/1/2023 | 6/30/2023 |
| 1/1/2023 | 3/31/2023 |
Student
| Learner | Course | Start |
| -------- | -------- |-------- |
| 1 | English | 11/5/23 |
| 1 | Math | 7/10/23 |
| 2 | English | 7/25/23 |
| 2 | Math | 5/15/23 |
| 3 | Science | 4/25/23 |
| 3 | Math | 7/25/23 |
| 3 | English | 11/15/23 |
| 4 | Science | 11/5/23 |
| 4 | Math | 1/5/23 |
If I only have a single date range to filter against, I can do this using filter() to filter by start dates, but I have a dozen different ranges and don't want to run in manually for each range. My intended outcome is a list of ranges with the students having a class in that range
| Start | End | Learner |
| ---------- | ----------- | -------- |
| 10/1/2023 | 12/31/2023 | 1 |
| 10/1/2023 | 12/31/2023 | 3 |
| 10/1/2023 | 12/31/2023 | 4 |
| 7/1/2023 | 9/30/2023 | 1 |
| 7/1/2023 | 9/30/2023 | 2 |
| 7/1/2023 | 9/30/2023 | 3 |
| 4/1/2023 | 6/30/2023 | 2 |
| 4/1/2023 | 6/30/2023 | 3 |
| 1/1/2023 | 3/31/2023 | 4 |
|
Apply criteria from one table against each row in another table to generate a list of matches |
|r|function|loops|vector|rstudio| |
null |