instruction stringlengths 0 30k ⌀ |
|---|
|javascript|reactjs| |
I am having an "Introduction to AI" course and we were assigned to do a mini project about a simple expert system using AIMA library in python (from the book AI: Modern Approach). I am having some difficulties in writing FOL knowledge base rules in this library particularly, in class they didn't provide us with enough examples and I am struggling to find any online resources.
|
Be careful to implement a solution that will not prepend `#` to an empty array. A good general solution should also not create an unnecessary trailing space. Ideally, a robust generalized solution should work regardless of the delimited value characters.
This will never generate any unwanted characters. Split the values by delimiter, prepend `#` to each value with `substr_replace(), then re-join with spaces.
Code: ([Demo][1])
echo implode(
' ',
substr_replace(
explode(',', $hashTagStr),
'#',
0,
0
)
);
[1]: https://3v4l.org/LR7H0 |
null |
{"Voters":[{"Id":26742,"DisplayName":"Sani Huttunen"},{"Id":367865,"DisplayName":"Ouroborus"},{"Id":62576,"DisplayName":"Ken White"}],"SiteSpecificCloseReasonIds":[16]} |
As of MongoDB 6.x it is possible to use relative path as data and log directory (not with tilde). For the below configuration (as an example), if the server is started from bin directory, it uses the data directory and the logs in the mentioned log file.
This is useful in cases of automated installation of MongoDB from tar.gz file, where the installation directory is not known in advance and var directory may not be accessible. The only alternative to the below is to modify the config YAML post installation to include the path to the data directory and log file (I have used the below only as an example, data and log should be outside of installation directory but could be relative to it).
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: ../log/mongod.log
# Where and how to store data.
storage:
dbPath: ../data |
To get the data set as insert commands without root user - using different user
pg_dump -U <dbUser> -a <DB schema> --column-inserts --data-only > backup.sql
data will be backed up into a backup.sql file |
You can do this using yup.lazy() to dynamically define the schema based on the value of type. Here's how you can modify your schema
code
```
const schema = yup.object({
questions: yup.array().of(
yup.lazy((value) =>
yup.object().shape({
subject: yup.string().required('Subject is required'),
subLevel: yup.string().required("Sublevel is required"),
difficultyLevel: yup.string().required("Difficulty level is required"),
type: yup.string().required("Answer type is required"),
name: yup.string().required("Question is required"),
image: yup.mixed().test('fileType', 'Invalid file format', (value) => {
if (!value || typeof value === 'string') return true;
const supportedFormats = ['image/jpeg', 'image/png'];
return supportedFormats.includes(value[0]?.type);
}),
correctOption: yup.string().when("type", {
is: "MCQ",
then: yup.string().required("You must enter at least one option"),
otherwise: yup.string().default('').notRequired(),
}),
})
)
),
});
``` |
Unable to ping remote websites from an ipV6 only ubuntu ec2 Instance |
I created a tic tac toe game and want to use GPT as player 2 but I keep getting errors.
import sys
import random
import openai
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
# Set your API key here
api_key = "YOUR_API_KEY"
# Initialize the OpenAI API client
openai.api_key = api_key
class TicTacToe(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Tic Tac Toe")
self.setGeometry(100, 100, 300, 300)
self.board = [[" " for _ in range(3)] for _ in range(3)]
self.current_player = "X"
self.buttons = []
for i in range(3):
row = []
for j in range(3):
button = QPushButton("", self)
button.setGeometry(j * 100, i * 100, 100, 100)
button.clicked.connect(lambda _, i=i, j=j: self.on_click(i, j))
row.append(button)
self.buttons.append(row)
def check_winner(self, player):
for row in self.board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(self.board[row][col] == player for row in range(3)):
return True
if all(self.board[i][i] == player for i in range(3)) or all(self.board[i][2-i] == player for i in range(3)):
return True
return False
def is_board_full(self):
return all(all(cell != " " for cell in row) for row in self.board)
def on_click(self, row, col):
if self.board[row][col] == " ":
self.board[row][col] = self.current_player
self.buttons[row][col].setText(self.current_player)
if self.check_winner(self.current_player):
QMessageBox.information(self, "Tic Tac Toe", f"Player {self.current_player} wins!")
self.reset_board()
elif self.is_board_full():
QMessageBox.information(self, "Tic Tac Toe", "It's a tie!")
self.reset_board()
else:
self.current_player = "O" if self.current_player == "X" else "X"
if self.current_player == "O":
|
How can I use open ai api key for my tic tac toe game |
|python|api|openai-api| |
null |
|python|scipy|permutation|t-test|scipy.stats| |
|python|mathematical-optimization|linear-programming|or-tools| |
I had this same issue when I deployed the problem was with the redirection from Vervel so what I did was make a vercel.json file and added `{"rewrites": [{"source":"/(.*)", "destination": "/"}]}` |
If the above solutions dont work for you, disabling GPG check worked for me immediately, since I could not make other suggestions work in the moment.
I edited the
`sudo vim /etc/yum.repos.d//etc/mysql-community.repo`
Then scroll to where you will find mysql version causing issues for me was 5.7
```
[mysql57-community]
name=MySQL 5.7 Community Server
baseurl=http://repo.mysql.com/yum/mysql-5.7-community/el/7/$basearch/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
```
Change `gpgcheck=1` to `gpgcheck=0` and try again the installation.
This will cause the system to ignore gpgcheck for mysql. Please note, security wise its not advisable, but its a quick work around if you are not concerned about packages security
|
{"OriginalQuestionIds":[78210393],"Voters":[{"Id":2937831,"DisplayName":"jakevdp","BindingReason":{"GoldTagBadge":"python"}}]} |
I'm learning c++ for micro-controller programming.
I've used python before.
I prefer to learn JavaScript at the same time and use Node.js framework because of its big community. Or should I go for Django framework?
Or another language and framework altogether?
Which one has a better job market?
My main goal is to enter the job market by learning and mastering that language and following its roadmap. Appreciate any guidance |
Which language I should use for back-end development? |
|backend|javascript|jobs|python| |
How can I type within a search box and have the letters I type turn bold from suggested words? For example, I type "he" in search bar and it looks like this as I type: **he**lp. Also, if I type in "lp" the text should appear: he**lp**.
I have some code written already and I just want to add this functionality to it, but not sure how to do this. Thank you.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// List toggle (search bar)
const searchBar = document.querySelector('#search-bar');
const searchList = document.querySelector('#search-list');
searchBar.addEventListener('click', () => {
searchList.style.display = "block";
});
const updateListState = e => {
const targetId = e.target.id;
if (targetId !== 'search-bar' && targetId !== 'search-list' && targetId !== 'search-bar-filler' && targetId !== 'search-bar-container' && targetId !== 'search-item-names' && targetId !== 'search-submit' && targetId !== 'search-submit-container') {
searchList.style.display = "none";
}
}
document.addEventListener('mousemove', updateListState);
// Letter search (search bar)
function search_items() {
let input = document.getElementById('search-bar').value
input = input.toLowerCase();
let x = document.getElementsByClassName('search-item-names');
for (i = 0; i < x.length; i++) {
if (!x[i].innerHTML.toLowerCase().includes(input)) {
x[i].style.display = "none";
}
else {
x[i].style.display = "list-item";
}
}
}
<!-- language: lang-css -->
#filler {
position: absolute;
background-color: red;
width: 20px;
height: 20px;
}
#search-list {
margin-top: 20px;
width: 150px;
height: 150px;
display: none;
}
<!-- language: lang-html -->
<div id="search-bar-container">
<input id="search-bar" type="text" name="search" onkeyup="search_items()" onclick="ListToggle()"
placeholder="Search items..">
<div id="search-bar-filler"></div>
<div id='search-list'>
<div id="search-item-names" class="search-item-names">Automotive Degreaser</div>
<div id="search-item-names" class="search-item-names">Beats by Dre</div>
<div id="search-item-names" class="search-item-names">JBL Partybox</div>
<div id="search-item-names" class="search-item-names">Makeup</div>
<div id="search-item-names" class="search-item-names">Mr Potato Head</div>
<div id="search-item-names" class="search-item-names">Olympus Camera</div>
<div id="search-item-names" class="search-item-names">Pillow</div>
<div id="search-item-names" class="search-item-names">RC Race Car</div>
<div id="search-item-names" class="search-item-names">Simon Rabbit</div>
<div id="search-item-names" class="search-item-names">Truth Hoodie</div>
</div>
</div>
<!-- end snippet -->
|
Find the sum of the numbers in the sequence |
|c++|string|sum|char|numbers| |
null |
One option to add images to your axis text would be to use the `ggtext` package which allows to add images to the axis text using an `<img>` and by using `ggtext::element_markdown()` for the axis text. However, I haven't found an option to center align the text and the image for the y axis text. Instead, for the y axis I use `geom_richtext` to add the images:
``` r
library(ggplot2)
library(ggtext)
chiMate <- data.frame(
pairType = c("assortative", "disassortative", "disassortative", "assortative", "disassortative", "disassortative", "assortative"),
Male_Phenotype = c("metallic", "rufipennis", "metallic", "militaris-a", "metallic", "militaris-a", "rufipennis"),
Female_Phenotype = c("metallic", "metallic", "militaris-a", "militaris-a", "rufipennis", "rufipennis", "rufipennis"),
exp = c(0.10204082, 0.11224490, 0.28571429, 0.10204082, 0.02040816, 0.08163265, 0.29591837),
obs = c(0.04081633, 0.02040816, 0.02040816, 0.03061224, 0.00000000, 0.00000000, 0.03061224)
)
labels <- c(
rufipennis = "<img src='https://i.stack.imgur.com/Q8BqO.png'
width='20' />",
"militaris-a" = "<img src='https://i.stack.imgur.com/EtdfR.png'
width='20' />",
metallic = "<img src='https://i.stack.imgur.com/YIDoA.png'
width='20' />"
)
p <- ggplot(chiMate, aes(x = Male_Phenotype, y = Female_Phenotype)) +
geom_point(aes(color = pairType, size = 2.1 * exp)) +
geom_point(color = "black", aes(size = 1.6 * exp)) +
geom_point(color = "white", aes(size = 1.3 * exp)) +
geom_point(aes(size = 1.25 * obs), color = "salmon") +
scale_color_manual("Pair type",
values = c(
"assortative" = "cornflowerblue",
"disassortative" = "aquamarine3"
)
) +
scale_size_continuous(range = c(10, 45)) +
scale_x_discrete(
expand = c(0, 1),
labels = \(x) paste0(labels[x], "<br>", x)
) +
scale_y_discrete(
expand = c(0, .8)
) +
geom_text(aes(label = round(obs, digits = 3))) +
# Add images for the y axis using ggtext::geom_richtext
# to vertically align with the axis text
ggtext::geom_richtext(
data = tibble::enframe(labels),
aes(y = name, label = value), x = -Inf,
fill = "white", label.color = NA, hjust = 0
) +
theme_minimal() +
labs(x = "Male Phenotype", y = "Female Phenotype", size = "Mate Count") +
theme(
legend.position = "bottom",
legend.box.background = element_rect(color = "black"),
axis.title = element_text(size = 14),
axis.text = ggtext::element_markdown(
size = 10, valign = 0
),
axis.text.y.left = ggtext::element_markdown(
size = 10, valign = 1
)
) +
coord_cartesian(clip = "off") +
guides(color = guide_legend(
override.aes = list(size = 12)
), size = "none")
p
```
<!-- --> |
null |
```
package main
import "fmt"
func square(c chan int) {
fmt.Println("[square] reading")
num := <-c
fmt.Println("[square] before writing")
c <- num * num
fmt.Println("[square] after writing")
}
func cube(c chan int) {
fmt.Println("[cube] reading")
num := <-c
fmt.Println("[cube] before writing")
c <- num * num * num
fmt.Println("[cube] after writing")
}
func main() {
fmt.Println("[main] main() started")
squareChan := make(chan int)
cubeChan := make(chan int)
go square(squareChan)
go cube(cubeChan)
testNum := 3
fmt.Println("[main] sent testNum to squareChan")
squareChan <- testNum
fmt.Println("[main] resuming")
fmt.Println("[main] sent testNum to cubeChan")
cubeChan <- testNum // Why main not blocked here?
fmt.Println("[main] resuming")
fmt.Println("[main] reading from channels")
squareVal, cubeVal := <-squareChan, <-cubeChan
sum := squareVal + cubeVal
fmt.Println("[main] sum of square and cube of", testNum, " is", sum)
fmt.Println("[main] main() stopped")
}
```
Why is it printed like that ???
Output:
1.[main] main() started
2. [main] sent testNum to squareChan
3. [cube] reading
4. [square] reading
5. [square] before writing
6. [main] resuming
7. [main] sent testNum to cubeChan
8. [main] resuming
9. [main] reading from channels
10. [square] after writing
11. [cube] before writing
12. [cube] after writing
13. [main] sum of square and cube of 3 is 36
14. [main] main() stopped
2 questions:
1) Why after call "squareChan <- testNum" scheduler first check cube goroutine instead of square goroutine?
2) Why after call "cubeChan <- testNum" main goroutine not blocked?
Please can somebody explain by steps - How exactly scheguler switch between square, cube and main goroutines in this code?
|
{"Voters":[{"Id":3689450,"DisplayName":"VLAZ"},{"Id":1940850,"DisplayName":"karel"},{"Id":546871,"DisplayName":"AdrianHHH"}],"SiteSpecificCloseReasonIds":[13]} |
Print Preview Multiple Sheets
-
**Column**
- You need to pass a 1D array without the use of the `Array` function. You can use the late-bound version of the `Transpose` worksheet function to convert the 2D array to a 1D array using the following:
Dim wb As Workbook: Set wb = ThisWorkbook
Dim MyArray As Variant: MyArray = Application _
.Transpose(wb.Sheets("Admin Sheet").Range("A1:A2").Value)
wb.Sheets(MyArray).PrintPreview
Here `MyArray` holds a 1D one-based array.
**Row**
- If you have the sheet names in a row (e.g. `A1:B1`), you need to wrap the right side of the `MyArray = ...` expression in yet another `Application.Transpose()`:
MyArray = Application.Transpose(Application. _
.Transpose(wb.Sheets("Admin Sheet").Range("A1:B1").Value))
Here `MyArray` holds a 1D one-based array.
**Arrays**
- `MyArray = ThisWorkbook.Sheets("Admin Sheet").Range("A1:A2").Value` returns a 2D one-based (single-column) array held by the `MyArray` variable. You can prove it with the following:
Debug.Print LBound(MyArray, 1), UBound(MyArray, 1), _
LBound(MyArray, 2), UBound(MyArray, 2)
Dim r As Long
For r = 1 To UBound(MyArray, 1)
Debug.Print MyArray(r, 1) ' !!!
Next r
- `MyArray = Application.Transpose(wb.Sheets("Admin Sheet").Range("A1:A2").Value)` will return a 1D one-based array held by the `MyArray` variable. You can prove it with the following:
Dim n As Long
For n = 1 To UBound(MyArray) ' or UBound(MyArray, 1)
Debug.Print MyArray(n) ' !!!
Next n
- `Dim Jag As Variant: Jag = Array(MyArray)` returns the 1D `MyArray` in the first element of another 1D (usually) zero-based array held by the `Jag` variable. This structure is called a jagged array or an array of arrays. You can prove it using the following:
Debug.Print LBound(Jag), UBound(Jag)
Dim j As Long
For j = LBound(Jag) To UBound(Jag)
For n = LBound(Jag(j)) To UBound(Jag(j)) ' !!!
Debug.Print j, n, Jag(j)(n) ' !!!
Next r
Next j |
I do a lot of Javascript programming that checks for the presence of something (library, window, socket) before executing code.
if (foo()) {
do this thing
}
Sometimes `foo()` gets set only once, but then I will check it over and over again during execution. React's `useRef()` is an good example.
const setRef = useRef(null)
setSomeRef = (someCondition)
if (someRef.current) { // someRef is defined and available
// repeatedly execute some function
}
My question: is repeatedly checking for the same, unchanging variable to be set during repeated execution a bottleneck? Can it be avoided? In the particular case of JavaScript, does memorization or some similar process make the check faster?
I get that this is a common thing to do (`while(true)` being example #1) but I'm interested in 1) the effect of these checks on program efficiency -- especially as relates to JavaScript and 2) alternative approaches. |
Do conditional checks cause bottlenecks in Javascript? |
|javascript|performance|optimization| |
My application is a learning platform which lets users to upskill themselves in basic areas of computers specifically for South East Asian nations.<br>
I am using **Azure AD B2C** for user management and using **Identity Experience Framework (Custom policies)**. <br>
Anyone can register at **<https://skillourfuture.org/register>**. Upon registration, the user will get an **email with the password** and simultaneously the user account gets created in both my application & B2C Tenant.<br>
When you login to this application using the [B2C Sign in Page](https://skillourfuture.b2clogin.com/skillourfuture.onmicrosoft.com/b2c_1a_signup_signin_only_signin_v3/oauth2/v2.0/authorize?client_id=8ffcd385-7640-4830-8d41-2b990716e0a2&redirect_uri=https%3A%2F%2Flearn.skillourfuture.org%2Fsignin-b2c&response_type=code&scope=openid%20profile%208ffcd385-7640-4830-8d41-2b990716e0a2%20offline_access&code_challenge=TFyMd_eNx0UYIzoFod7ivb0km6VJdmt66szC3Uwpoto&code_challenge_method=S256&response_mode=form_post&nonce=638474960767205458.MTIyYmYyMzUtMTMxOS00MGMyLThjNGQtN2M4NmNlZTk1MDhiYTM3NGExMDktMDczMC00M2ExLTgyNTgtNjhkN2Q5YzA4MDMx&client_info=1&x-client-brkrver=IDWeb.1.3.0.0&state=CfDJ8Napqmltq1dCqCa23z7w3M74bLIYHpMoQQ6wg5kH9Vq7mTG3gIaPQeZqwjT3tFOaPWshPjmxTqGiZNqMnrT3uJaHhDjNzIq3lBW1Yma1oEjQrt_-SQx0r7e-mfZgPC-riYjNZeWPcp9AiESexIgoOcpRG2vqVWASA3gorr7vZs3VXL2WYQwC3ypSIpXNsDB2wcpeVAFnUKfyYV6UtEKWsX4Nj1u4NuvWIe24v8APywWYSVdIGwWguB-WoF_EOcIxCLneWN910fL2axdorehfgl8Qq28v3C4Rw3Gg6JXMHs2xQVkXK1Olhp858jAqSdyGyGvt3N6kjRWcwvtZaqY9B78m496Lv1vqb7LPKll42d_0bdAETl5wsopRZLrwQTe8Y35Q6y-tl9Ftlc359izoZvyN-OyiJYpwMNv1iboQBh041OXY0DG85US3M3mKHbgBFor4YH2RbFznq7TnN4UlpHo&x-client-SKU=ID_NET6_0&x-client-ver=6.21.0.0), I am getting an error page of Microsoft with the URL ````https://learn.skillourfuture.org/MicrosoftIdentity/Account/Error````
When you click on the ````Home```` button on the error page, you will be redirected to our Homepage which is **<https://learn.skillourfuture.org>**. When you click on ````Sign in```` button on top right corner, you will directly login to the application without entering the credentials.<br>
I want to get rid of the error when user logs in for the first time. I've logged multiple tickets with MS B2C team, but of no use.<br>
The reason we want to use the B2C Sign in page URL is that we have implemented various languages and we will send the Sign in pages & content according to the users region.<br>
Any possible solutions or work-around is appreciated
<br><br>
[![Microsoft Error Page mentioned above][1]][1]
<br>PS: When you enter the credentials, they are getting stored in the cache and when you click on Sign in button of of my homepage, it is taking the cached creds and letting you in.
[1]: https://i.stack.imgur.com/e74Rn.jpg |
B2C Login is showing me an error page after entering credentials. When clicked on Sign in button, it's logging me in without asking for creds |
|azure-ad-b2c|azure-ad-b2c-custom-policy| |
Need to calculate Matrix exponential with Tailor series with MPI matrix is small 3 x 3 for example
Meanwhile
```
vector<vector<double>> matrixMult(const vector<vector<double>>& A, const vector<vector<double>>& B) {
int n = A.size();
vector<vector<double>> C(n, vector<double>(n, 0));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
return C;
}
vector<vector<double>> matrixExp(const vector<vector<double>>& A) {
int n = A.size();
vector<vector<double>> E(n, vector<double>(n, 0));
vector<vector<double>> T(n, vector<double>(n, 0));
vector<vector<double>> localE(n, vector<double>(n, 0));
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
for (int i = 0; i < n; i++)
E[i][i] = 1;
for (int i = 0; i < n; i++)
localE[i][i] = 0;
T = E;
for (int j = 1; j <= rank; j++)
{
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = T;
for (int i = rank + 1; i <= N; i += size) {
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = matrixSum(localE, T);
}
MPI_Reduce(localE[0].data(), E[0].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[1].data(), E[1].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[2].data(), E[2].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
return E;
}
```
But i dont know how to optimize this
```
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
```
Maybe it's impossible with this implementation
[scheme][1]
[1]: https://i.stack.imgur.com/Lc65Z.png |
Attempted to use the below code to cause the GitHub actions to start when the release tag is published, but it isn't working.
```yaml
name: Update Values on Release
on:
release:
types: [ published ] # Trigger only on published releases
jobs:
update_values:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
git config --global user.email "xxxxxx@gmail.com"
git config --global user.name "pxjssjsjx"
release_tag=${{ github.event.release.tag_name }}
# Update the value in the specified file (replace with your details)
npx yaml-update -f hackkerRankSolutions/actions.yaml version=$release_tag
git add hackkerRankSolutions/actions.yaml
git commit -m "Update version to $release_tag in actions.yaml"
git push origin main
```
|
null |
Using Conditional Formatting does not restrict the automation.<br>
Rather than colouring the cells in Pandas and writing to Excel you are just colouring the cells in Excel instead, using Openpyxl to apply Conditional Formatting.<br>
It shouldn't be any different unless you have a need to access the DataFrame with styling included for some reason.<br>
Conditional Formatting does have the advantage that if your need to change any values manually in Excel for whatever reason, the fill colour will update automatically.<br>
Anyway you can make your choice what works better for your scenario.
As @Vikas notes it would be better if you provided your dataframe and expected result so I'm guessing what your data might look like based on your code.<br>
It seems the DF has numeric values and you want to background colour based on;
1. Values from 0 to 1, Gradient colour from White to Yellow
2. Values from 1 to 500 solid colour 'dimgrey'
3. Values from 500 to 1000 solid colour 'lightgrey'
4. Values over 1000 no background colour
In this example I have a DataFrame with various values to cover the 4 ranges above. After writing the DF to excel we use Openpyxl to apply the Conditional Formatting.
```
import pandas as pd
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule
from openpyxl.styles import PatternFill
from openpyxl.styles.differential import DifferentialStyle
df = pd.DataFrame({
'ID': range(1, 5),
'col1': [0.1, 0.99, 501, 0.01],
'col2': [0.4, 1001, 0.6, 489],
'col3': [10, 0.15, -0.67, 0.89],
'col4': [0.35, 127, 0.40, 867]
})
excel_file = 'styled_df.xlsx'
sheet_name = 'Sheet1'
### Define Style colours
white_fill = PatternFill(start_color='FFFFFF', end_color='FFFFFF', fill_type='solid')
dim_grey_fill = PatternFill(start_color='696969', end_color='696969', fill_type='solid')
light_gray_fill = PatternFill(start_color='D3D3D3', end_color='D3D3D3', fill_type='solid')
### Conditional Format Range
cf_range = "B2:E5"
### Write the DataFrame to Excel
with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name=sheet_name, header=True, index=False)
ws = writer.book[sheet_name]
### CF Rule1; Values greater than 1000 fill background with white (no colour)
rule_def = CellIsRule(operator="greaterThan",
formula=[1000],
stopIfTrue=False)
rule.dxf = DifferentialStyle(fill=white_fill)
ws.conditional_formatting.add(cf_range, rule_def)
### CF Rule1; Values between > 1 and 500 fill background with dim_grey
rule1 = CellIsRule(operator="between",
formula=[1.01, 500],
stopIfTrue=False)
rule1.dxf = DifferentialStyle(fill=dim_grey_fill)
ws.conditional_formatting.add(cf_range, rule1)
### CF Rule2; Values > 500 and 1000 fill background with light_gray
rule2 = CellIsRule(operator='between',
formula=[500.01, 1000],
stopIfTrue=False)
rule2.dxf = DifferentialStyle(fill=light_gray_fill)
ws.conditional_formatting.add(cf_range, rule2)
### CF Rule3; Values 0 and 1 fill background with gradient from White (0) to Yellow (1)
rule3 = ColorScaleRule(start_type='num', start_value=0.1, start_color='FFFFFFFF',
end_type='num', end_value=1, end_color='FFFFFF00')
ws.conditional_formatting.add(cf_range, rule3)
```
The data in Excel will look like this<br>
CF is applied to cells in the range B2:E5. As noted if you change a value the bg colour will update to suit.<br>
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/T1IhG.png |
Why is the main goroutine not blocked after write in unbuffered channel? |
|go| |
null |
To achieve the menu popup functionality, you should prefer using `checkbox input` of HTML alongside with the `:checked` CSS property.
Try following the given example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
body {
user-select: none;
}
#content {
display: none;
width: 40%;
margin-top: 4px;
padding: 8px;
background: skyblue;
border-radius: 6px;
cursor: pointer;
}
label {
color: #292929;
cursor: pointer;
}
label:hover {
text-decoration: underline;
}
label:active {
color: black;
}
#toggle:checked+#content {
display: block;
}
#toggle {
/** display: none; (to hide the checkbox icon) **/
}
<!-- language: lang-html -->
<label for="toggle">Press here to show content</label>
<input type="checkbox" id="toggle">
<div id="content">
If pressed content is shown
</div>
<!-- end snippet -->
|
Input a string and print the sum of the numbers in the string
Input: abc123kjewd456
Output: 579
I want code it with pointer in string, array, loop, and lots of way, Can you help me use the best way? I can give you full of subject: Securing user information today is a problem for every computer user. To increase the security of his account, Nam decided to hide his password using a code sequence consisting of characters in the English alphabet and numbers. Since I haven't used it for a long time, I can't remember it. I want to ask you programmers to help me find the password. The password is the sum of the numbers in the sequence. |
Recognising what you say about timestamps, **ImageMagick** has exactly such a feature. First, an example.
Here I create two images with identical pixels but a timestamp at least 1 second different:
convert -size 600x100 gradient:magenta-cyan 1.png
sleep 2
convert -size 600x100 gradient:magenta-cyan 2.png
[![enter image description here][1]][1]
If I checksum them on macOS, it tells me they are different because of the embedded timestamp:
md5 -r [12].png
c7454aa225e3e368abeb5290b1d7a080 1.png
66cb4de0b315505de528fb338779d983 2.png
But if I checksum **just the pixels** with **ImageMagick**, (where `%#` is the pixel-wise checksum), it knows the pixels are identical and I get:
identify -format '%# - %f\n' 1.png 2.png
70680e2827ad671f3732c0e1c2e1d33acb957bc0d9e3a43094783b4049225ea5 - 1.png
70680e2827ad671f3732c0e1c2e1d33acb957bc0d9e3a43094783b4049225ea5 - 2.png
And, in fact, if I make a `TIFF` file with the same image contents, whether with Motorola or Intel byte order, or a NetPBM `PPM` file:
convert -size 600x100 gradient:magenta-cyan -define tiff:endian=msb 3motorola.tif
convert -size 600x100 gradient:magenta-cyan -define tiff:endian=lsb 3intel.tif
convert -size 600x100 gradient:magenta-cyan 3.ppm
**ImageMagick** knows they are the same, despite different file format, CPU architecture and timestamp,:
identify -format '%# - %f\n' 1.png 3.ppm 3{motorola,intel}.tif
70680e2827ad671f3732c0e1c2e1d33acb957bc0d9e3a43094783b4049225ea5 - 1.png
70680e2827ad671f3732c0e1c2e1d33acb957bc0d9e3a43094783b4049225ea5 - 3.ppm
70680e2827ad671f3732c0e1c2e1d33acb957bc0d9e3a43094783b4049225ea5 - 3motorola.tif
70680e2827ad671f3732c0e1c2e1d33acb957bc0d9e3a43094783b4049225ea5 - 3intel.tif
---
So, in answer to your question, I am suggesting you shell out to **ImageMagick** with the Python subprocess module and use **ImageMagick**.
Alternatively, you can use [wand][2] which is a ctypes binding to **ImageMagick**.
[1]: https://i.stack.imgur.com/X55wZ.png
[2]: https://pypi.org/project/Wand/ |
How to bold matched letters when typing in search box using javascript? |
|javascript|autocomplete|searchbar|bold| |
I recently upgraded my application from Laravel 10 to Laravel 11 using Laravel Shift.
After the upgrade I noticed that my private channels with Pusher are no longer authenticating. The error logs in Pusher's console contain are filled with "Auth info required to subscribe to private-users.2".
I noticed that in Laravel 11's documentation they dropped the bit about using an authorizer() function when setting up the Laravel Echo instance. Not sure if this is related to that? I left it in for now.
I confirmed that the call to "broadcasting/auth" is hitting the "Illuminate\Broadcasting › BroadcastController@authenticate" controller, however the request never seems to make it to the channel authorization callback. It returns and empty 200 response.
In my channels.php I've set the channel below
```
Broadcast::channel('users.{id}', UsersChannel::class);
```
And here's UsersChannel
```
<?php
namespace App\Broadcasting;
use App\Models\User;
class UsersChannel
{
/**
* Create a new channel instance.
*/
public function __construct()
{
//
}
/**
* Authenticate the user's access to the channel.
*/
public function join(User $user, int $id): array|bool
{
return (int) $user->id === (int) $id;
}
}
```
I also see the channel listed when using the command "php artisan channel:list"
Anyone know if there's an implicit change I'm overlooking for Laravel 11?
I've verified that channels.php is present in the new bootstrap\app.php. I also ran the "php artisan install:broadcasting" command, so everything should be properly registered after the update. |
Laravel 11 - Private channel authorization failing after upgrade from Laravel 10 |
|broadcasting|laravel-11| |
null |
|javascript|vercel| |
I want to iterate a chunk of code across columns in a dataframe, to create a new matrix of results. I am getting stuck with how to iteratively create new objects and matrices using/named after values in a certain column (Site) in my dataframe, to then pass through to the following lines of code.
The code I am wanting to iterate is:
```
SiteX_data = data %>% subset(Site == X) %>%select(x_coord, y_cood)
SiteX_dists <- as.matrix(dist(SiteX_data))
SiteX_dists.inv <- 1/SiteX_dists
diag(SiteX_dists.inv) <- 0
Resid_taxaX_siteX <- as.vector( Resid_data %>% subset(Site == X) %>% select(Abundance_TaxaX) )
Moran.I(Resid_taxaX_siteX, SiteX_dists.inv)
```
Where "X" refers to Site values in a dataframe (data):
| Sample | Site | Treatment | x_coord | y_coord | Abundance_Taxa_1 | ... | Abundance_Taxa_n
| ------ | ---- | -------- | ------- | ------- | ---------------- | --- | ----------------
| I1S1 | I1 | Inside | 140.00 | -29.00 | 56 | ... | 0
| O2S1 | O2 | Outside | 141.00 | -28.00 | 3 | ... | 100
| O2S2 | O2 | Outside | 141.10 | -28.10 | 5 | ... | 4
And "Y" refers to unique "Abundance_Taxa" columns in a separate dataframe (Resid_data):
|Site | Abundance_Taxa_1 | ... | Abundance_Taxa_n |
|-----| ---------------- | --- | ---------------- |
|O1 | -0.5673 | --- | 1.1579 |
|I1 | -0.6666 | --- | 1.2111 |
There are multiple "Samples" for each "Site". The first four lines of code aim to use the x and y coordinates to create a distance matrix for each site, then simply invert the distances.
The fifth line aims to create a vector of the values in Resid_data for each site and taxa.
The final line of code uses the taxa/site vector and the previously created distance matrix to calculate Moran's I for each site and taxa.
My desired outcome is to produce the following matrix:
| Site | Treatment | MoranI_Taxa_1 | ... | MoranI_Taxa_n|
| ---- | -------- | ------------- | --- | -------------|
| I1 | Inside | 0.1 | ... | 0.2 |
| O2 | Outside | 0.5 | ... | 0.01 |
I am not sure how to write this so that
- in the first 4 lines I can iteratively create a distance matrix for each site, named after that site, to later pass through to the final line
- iterate the 5th line of code for each site and taxa in Resid_data (i.e., all columns beginning with "Abundance_Taxa_"), and create a vector for each
- iterate the final line for each site (e.g., for site 1, it would repeat as:
```
Moran.I(Resid_taxa1_site1, Site1_dists.inv)
Moran.I(Resid_taxa2_site1, Site1_dists.inv)
```
until it has completed for all vectors of residual values for that site).
The number of Site values is relatively small (12), but the number of "Abundance_Taxa" columns that I need to iterate through is large (~2400). Most of what I have found online has been writing very simple 'for' loops. As such, I don't even really know where to start with this. |
I have a blank project with nothing but a code snippet from Bootstraps horizontal gutters page https://getbootstrap.com/docs/5.3/layout/gutters/#horizontal-gutters
I dont see any horizontal gaps, why is that? Vertical gutters only work...
[image](https://i.stack.imgur.com/1uull.png)
<div class="container text-center">
<div class="row g-2">
<div class="col-6 border">
<div class="p-3">Custom column padding</div>
</div>
<div class="col-6 border">
<div class="p-3">Custom column padding</div>
</div>
<div class="col-6 border">
<div class="p-3">Custom column padding</div>
</div>
<div class="col-6 border">
<div class="p-3">Custom column padding</div>
</div>
</div>
</div>
https://pastebin.com/raw/UXU2ePk2
https://pastebin.com/raw/cnBsCPvF |
Bootstrap horizontal gutters issue |
|html|css|bootstrap-5| |
null |
I have a tree, implemented as a nested dictionary, and I need to come up with a way for the user to choose two nodes, one of which must be a descendant of the other.
A simple drop-down would probably work, but I wanted to indent the options to clearly communicate which "child" option descends from which "parent" option. I think normally this would be done with `<optgroup>`, but IINM these can't nest inside each other, and I need a solution that works for any arbitrarily deep tree.
So I did some digging around and apparently a sort of hacky way to do the indenting thing is to add a bunch of ` ` to the label of the options that are supposed to be indented. (see also [this][1] and [this][2]) So that's what I did:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let g_pLanguageTree = {
"Name": "Indo-European",
"Children": [
{
"Name": "Germanic",
"Children": [
{
"Name": "North Germanic",
"Children": [
{
"Name": "Norwegian",
"Children": []
},
{
"Name": "Swedish",
"Children": []
},
{
"Name": "Danish",
"Children": []
}
]
},
{
"Name": "West Germanic",
"Children": [
{
"Name": "German",
"Children": []
},
{
"Name": "Dutch",
"Children": []
},
{
"Name": "English",
"Children": []
}
]
},
{
"Name": "East Germanic",
"Children": [
{
"Name": "Gothic",
"Children": []
}
]
}
]
},
{
"Name": "Italic",
"Children": [
{
"Name": "Umbrian",
"Children": []
},
{
"Name": "Oscan",
"Children": []
},
{
"Name": "Latin",
"Children": [
{
"Name": "Spanish",
"Children": []
},
{
"Name": "French",
"Children": []
},
{
"Name": "Italian",
"Children": []
},
{
"Name": "Portuguese",
"Children": []
},
{
"Name": "Romanian",
"Children": []
}
]
},
]
},
{
"Name": "Anatolian",
"Children": [
{
"Name": "Hittite",
"Children": []
},
{
"Name": "Luwian",
"Children": []
}
]
},
{
"Name": "Armenian",
"Children": []
}
]
}
function CreateStageDropdown(pRootStage = g_pLanguageTree) {
let eDropDown = document.createElement("select");
document.getElementById("MainDiv").appendChild(eDropDown);
let tOptions = CreateStageDropdown_Options(pRootStage, 0);
for (let i = 0; i < tOptions.length; i++) {
let eOption = document.createElement("option");
eOption.label = tOptions[i];
eOption.value = i;
eDropDown.appendChild(eOption);
}
eDropDown.addEventListener("change", function(Event) {
let sIn = eDropDown.value;
let eSelected = eDropDown.querySelector("option[value = '"+sIn+"']");
let sOut = tOptions[sIn].replaceAll(/\s*/g,"");
eDropDown.label = sOut;
});
return [eDropDown, tOptions];
}
function CreateStageDropdown_Options(pStage, iNestingLayers) {
let tOptions = [];
tOptions.push("\u00A0\u00A0\u00A0\u00A0".repeat(iNestingLayers)+pStage.Name);
let tChildren = pStage.Children;
if (tChildren.length > 0) {
for (let i = 0; i < tChildren.length; i++) {
let pChild = tChildren[i];
tOptions.push(CreateStageDropdown_Options(pChild, iNestingLayers + 1));
}
}
tOptions = tOptions.flat();
return tOptions;
}
<!-- language: lang-html -->
<div id="MainDiv">
<input type="button" value="Click to create dropdown" onclick="CreateStageDropdown()"/>
</div>
<div id="OtherDiv">
<input type="button" value="Click to create dropdown (Just Germanic)" onclick="CreateStageDropdown(g_pLanguageTree.Children[0])"/>
</div>
<!-- end snippet -->
It recursively traverses the dictionary, adding more spaces to the start of the options' names every time it has to go down a level in the tree.
This sort of works, but it looks really wonky how the final label that shows up in the box when an option is selected and the dropdown is closed, is so inconsistently aligned. Sometimes it's aligned left, sometimes it's slightly off center, sometimes it's all the way to the right.
So I've been trying to find a way to remove all the non-breaking spaces from the label of the `select` element itself when the dropdown is closed, and have them *only* show up in the labels of the `option`s that show up when the dropdown is open. You can see I was trying to do that in the event listener, by using a regex to replace all the whitespace with nothing, but eh... apparently `select` doesn't have a `label` attribute?
Is there no way to set the text of the `select` element independent of the label of the `option` that's been selected?
[1]: https://stackoverflow.com/questions/1146789/rendering-a-hierarchy-of-options-in-a-select-tag
[2]: https://stackoverflow.com/questions/8987028/best-modern-way-of-creating-indentation-in-a-select |
De-indenting the label of a <select> with with indented options |
|javascript|html|select|parent-child|indentation| |
https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.base.scalar
> **Warning**
Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:
> <?php
> function test(boolean $param) {}
> test(true);
> ?>
> The above example will output:
> > Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given
So in a nutshell, `boolean` is an alias for `bool`, and aliases don't work in type hints.
Use the "real" name: **bool**
----------------------------
There are no similarity between [`Type Hinting`][1] and [`Type Casting`][2].
_Type hinting_ is something like that you are telling your function which type should be accepted.
_Type casting_ is to "switching" between types.
> The casts allowed are:
>
> (int), (integer) - cast to integer
> (bool), (boolean) - cast to boolean
> (float), (double), (real) - cast to float
> (string) - cast to string
> (array) - cast to array
> (object) - cast to object
> (unset) - cast to NULL (PHP 5)
In php _type casting_ both (bool) and (boolean) are the same.
[1]: http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
[2]: http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting |
{"OriginalQuestionIds":[44009037],"Voters":[{"Id":285587,"DisplayName":"Your Common Sense","BindingReason":{"GoldTagBadge":"php"}}]} |
I created a tic tac toe game and want to use GPT as player 2 but I keep getting errors.
```
import sys
import random
import openai
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
# Set your API key here
api_key = "YOUR_API_KEY"
# Initialize the OpenAI API client
openai.api_key = api_key
class TicTacToe(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Tic Tac Toe")
self.setGeometry(100, 100, 300, 300)
self.board = [[" " for _ in range(3)] for _ in range(3)]
self.current_player = "X"
self.buttons = []
for i in range(3):
row = []
for j in range(3):
button = QPushButton("", self)
button.setGeometry(j * 100, i * 100, 100, 100)
button.clicked.connect(lambda _, i=i, j=j: self.on_click(i, j))
row.append(button)
self.buttons.append(row)
def check_winner(self, player):
for row in self.board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(self.board[row][col] == player for row in range(3)):
return True
if all(self.board[i][i] == player for i in range(3)) or all(self.board[i][2-i] == player for i in range(3)):
return True
return False
def is_board_full(self):
return all(all(cell != " " for cell in row) for row in self.board)
def on_click(self, row, col):
if self.board[row][col] == " ":
self.board[row][col] = self.current_player
self.buttons[row][col].setText(self.current_player)
if self.check_winner(self.current_player):
QMessageBox.information(self, "Tic Tac Toe", f"Player {self.current_player} wins!")
self.reset_board()
elif self.is_board_full():
QMessageBox.information(self, "Tic Tac Toe", "It's a tie!")
self.reset_board()
else:
self.current_player = "O" if self.current_player == "X" else "X"
if self.current_player == "O":
```
|
You can split your dataset ( `split(data, ~Race)` ) and work with 3 distance matrices instead of one. Though this is bit more convenient with `sf` & `dplyr` where you can just group points by some attribute and then get the number of points within the distance from each of those locations.
``` r
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(dplyr)
library(ggplot2)
# generate example dataset
set.seed(42)
data <- data.frame(
id = as.factor(1:7),
X = runif(7, -.005, .005),
Y = runif(7, -.005, .005),
race = sample(c("white", "hispanic", "black"), 7, replace = TRUE))
data
#> id X Y race
#> 1 1 0.0041480604 -0.0036533340 white
#> 2 2 0.0043707541 0.0015699229 white
#> 3 3 -0.0021386047 0.0020506478 hispanic
#> 4 4 0.0033044763 -0.0004225822 hispanic
#> 5 5 0.0014174552 0.0021911225 hispanic
#> 6 6 0.0001909595 0.0043467225 black
#> 7 7 0.0023658831 -0.0024457118 black
# convert to sf object
data_sf <-
st_as_sf(data, coords = c("X", "Y"), crs = "WGS84")
# count points within distance, count includes origin point
# n_within : all points within 500m radius
# n_within_grouped : points from the same group within 500m radius
counts_sf <-
data_sf |>
mutate(n_within = st_is_within_distance(geometry, dist = 500) |> lengths()) |>
mutate(n_within_grouped = st_is_within_distance(geometry, dist = 500) |> lengths(), .by = race)
```
Resulting dataset with grouped and ungrouped counts and plot with point buffers. E.g. check "5" : total size of that neighbourhood is 5 while grouped count (number of triangle-points within 5's buffer) is 3.
``` r
counts_sf
#> Simple feature collection with 7 features and 4 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: -0.002138605 ymin: -0.003653334 xmax: 0.004370754 ymax: 0.004346722
#> Geodetic CRS: WGS 84
#> id race geometry n_within n_within_grouped
#> 1 1 white POINT (0.00414806 -0.003653... 3 1
#> 2 2 white POINT (0.004370754 0.001569... 4 1
#> 3 3 hispanic POINT (-0.002138605 0.00205... 3 2
#> 4 4 hispanic POINT (0.003304476 -0.00042... 5 2
#> 5 5 hispanic POINT (0.001417455 0.002191... 5 3
#> 6 6 black POINT (0.0001909595 0.00434... 3 1
#> 7 7 black POINT (0.002365883 -0.00244... 4 1
ggplot(counts_sf) +
# 500m buffers around points
geom_sf(data = st_buffer(counts_sf, 500), aes(color = id, fill = id), alpha = .1) +
geom_sf(aes(color = id, shape = race), size = 3) +
geom_sf_text(aes(label = id), nudge_x = -.0004)+
scale_color_brewer(palette = "Dark2") +
scale_fill_brewer(palette = "Dark2") +
ggspatial::annotation_scale() +
theme_minimal()
```
<!-- -->
<sup>Created on 2024-03-31 with [reprex v2.1.0](https://reprex.tidyverse.org)</sup>
|
> In my project I am trying to use `net.sf.saxon.s9api.XsltTransformer` in multiple threads using synchronization in java because as per documentation An XsltTransformer must not be used concurrently in multiple threads. It is safe, however, to reuse the object within a single thread to run the same stylesheet several times. Running the stylesheet does not change the context that has been established. Some of the public methods are synchronized: this is not because multi-threaded execution is supported, rather it is to reduce the damage if multi-threaded execution is attempted. but while trying to make stress test using JMeter by sending 100 request per second I found that `net.sf.saxon.s9api.XsltTransformer.transform()` takes more time and sometimes reach to 6 mins.
How can I use `net.sf.saxon.s9api.XsltTransformer.transform()` in multiple threads without impacting performance?
I tried to make class TransformerSingleton as below
```
public class TransformerSingleton {
private static XsltTransformer transformer;
private TransformerSingleton() {
}
public static void xsltLoad() {
if (transformer == null) {
synchronized (XsltTransformer.class){
try {
Processor processor = new Processor(false);
XsltCompiler compiler = processor.newXsltCompiler();
XsltExecutable xslt = compiler.compile(new StreamSource("/my_path/"));
transformer = xslt.load();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static XsltTransformer getTransformer(){
if (transformer == null) {
synchronized (XsltTransformer.class) {
xsltLoad();
}
} return transformer;
}
}
```
```
public static void main(String[] args) {
XsltTransformer transformer = XsltTransformerSingleton.getTransformer();
String xml = "<Users><name>AAA</name></Users>"; // for example
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes())) {
synchronized (transformer){
Transformer.setSource(new StreamSource(byteArrayInputStream));
XdmDestination chainResult = new XdmDestination();
Transformer.setDestination(chainResult);
Transformer.transform();
}
}
}
```
expected to make throughput reach to 100 requests per second.
actual I reached to 60 per second. |
the problem i had was error on microsoft visiual, mention befor the error of wheel of panda, needed the package of that before install pandas with pip install. now after install the microsoft visiual then use pip install panda and then pip install transform i had no errors. |
I've tried this:
<p class="post-date">
<time datetime="2023-01-01" th:text="${#temporals.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')}">Oct 5, 2023</time>
</p>
where `createdDate` is a `java.util.Date`
but I am getting this error:
2024-03-30 17:15:58.620 ERROR [] o.a.c.c.C.[.[.[.[dispatcherServlet]@log(175) - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#temporals.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')" (template: "blog-details" - line 109, col 49)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method format(java.sql.Timestamp,java.lang.String) cannot be found on type org.thymeleaf.expression.Temporals
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:237)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:147)
at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:400)
|
I am working on a practice project to create 3 separate pages that is Brand Page, Car Model Page and Car Model Variant detail page.
I am working on a project with three models car brands, car model, car model variants
When an user opens the Car model page they should see the list of variants in that car model
```
class BrandName(models.Model):
FullName = models.CharField(max_length= 100)
Slogan = models.CharField(max_length = 255)
slug = models.SlugField(unique=True)
def __str__(self):
return f"{self.FullName}"
class CarModel(models.Model):
Brand = models.ForeignKey(BrandName, on_delete = models.CASCADE,null=True, related_name = "brands")
ModelName = models.CharField(max_length = 200)
slug = models.SlugField(unique=True)
def __str__(self):
return f"{self.ModelName}"
class CarModelVariant(models.Model):
ModelVariantName = models.CharField(max_length = 100)
Brandname = models.ForeignKey(BrandName, on_delete = models.CASCADE, null = True, related_name="brands1")
Model1 = models.ForeignKey(CarModel, on_delete = models.CASCADE, null = True, related_name = "model1")
Doors = models.IntegerField
SeatingCapacity = models.IntegerField
def __str__(self):
return f"{self.ModelVariantName}"
```
# **In views.py of the app
# **
```
from django.shortcuts import render
from django.http import HttpResponse
from . models import CarModelVariant, CarModel, BrandName
from django.views.generic import ListView, DetailView
class CarModelVariantView(ListView):
template_name = "carlist.html"
model = CarModelVariant
def get_queryset(self):
list_model = super().get_queryset()
data = list_model.filter(Model1= CarModel_instance)
return data
```
# In urls.py of the app
#
`from django.urls import path
from . import views
urlpatterns = [
path("<slug:slug>", views.CarModelVariantView.as_view())
]`
I am facing a blank page while loading carlist.html template
```
`{% extends "base.html" %}
{% block title%}
Car Brand Variants List
{% endblock%}
{% block content %}
<ul>
{% for variant in data %}
<li>{{ variant }}</li>
{% endfor %}
</ul>
{% endblock %}`
``` |
Another way to do this is to inject the web socket server into a custom Jest environment. I had to do this due to `Websocket is not a constructor` error.
In your jest.config.js file
```
...
testEnvironment: "./custom-dom-environment.",
...
```
custom-dom-environment.js
```js
// my-custom-environment
const JsDomEnvironment = require('jest-environment-jsdom').TestEnvironment;
class CustomEnvironment extends JsDomEnvironment {
constructor(config, context) {
super(config, context);
}
async setup() {
await super.setup();
// Allow setting up a websocket server in jsdom environment
this.global.WebSocketServer = require('ws');
}
async teardown() {
await super.teardown();
}
getVmContext() {
return super.getVmContext();
}
}
module.exports = CustomEnvironment;
```
|
I haven't done anything in 68k assembly yet, so I can't vouch for it, but [Retro68](https://github.com/autc04/Retro68) should have a 68k-compatible version of GNU Assembler and the rest of the tooling needed to make Macintosh applications with it, given its description and my understanding of GCC's architecture:
> A GCC-based cross-compilation environment for 68K and PowerPC Macs. Why? Because there is no decent C++17 Compiler targeting Apple's System 6. If that's not a sufficient reason for you, I'm sure you will find something more useful elsewhere.
According to the requirements, it runs on Linux, macOS, and, for Windows, via [Cygwin](https://www.cygwin.com/). The README says the sample programs demonstrate how to produce BasiliskII/SheepShaver-compatible data/resource pairs, Executor-compatible AppleDouble pairs, MacBinary files, and HFS disk images. |
Here's a way to generate the arguments dynamically. This is written for Windows `msvcrt` but should work for `libc` as well:
**test.cpp**
```c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
for(int i = 0; i < argc; ++i)
printf("argv[%d] = \"%s\"\n", i, argv[i]);
printf("TEST1=%s\n", getenv("TEST1"));
printf("TEST2=%s\n", getenv("TEST2"));
return 0;
}
```
**test.py**
```py
import ctypes as ct
dll = ct.CDLL('msvcrt')
dll._execve.argtypes = ct.c_char_p, ct.POINTER(ct.c_char_p), ct.POINTER(ct.c_char_p)
dll._execve.restype = ct.c_ssize_t
cmd = b'test.exe'
args = [b'arg1', b'arg2', b'arg3']
env = [b'TEST1=hello', b'TEST2=goodbye']
# Convert Python lists to c_char_p arrays.
# Arrays should be null-terminated so adds None to the end.
cargs = (ct.c_char_p * (len(args) + 2))(cmd, *args, None)
cenv = (ct.c_char_p * (len(env) + 1))(*env, None)
dll._execve(cmd, cargs, cenv)
```
**Output:**
```none
argv[0] = "test.exe"
argv[1] = "arg1"
argv[2] = "arg2"
argv[3] = "arg3"
TEST1=hello
TEST2=goodbye
``` |
I had similar problems with webpack 5 and http-proxy-middleware.
The issue is webpack DevServer is using the `/ws` path, but my proxy and socket server were also using `/ws`.
**Option 1**
Before: proxy and socket server were using `/ws`.
```js
const setupProxy = [
createProxyMiddleware('/api', options),
createProxyMiddleware('/ws', { ...options, ws: true }),
];
module.exports = (app) => app.use(setupProxy);
```
After: change to use `/wss`, or anything else.
```js
const setupProxy = [
createProxyMiddleware('/api', options),
createProxyMiddleware('/wss', { ...options, ws: true }),
];
module.exports = (app) => app.use(setupProxy);
```
**Option 2**
Alternatively, you could modify webpack's socket `pathname`.
Docs: https://webpack.js.org/configuration/dev-server/#websocketurl
Fix: https://github.com/webpack/webpack/discussions/15520#discussioncomment-2343375 |
I'm struggling to solve the following problem. My window top left corner has negative coordinates when maximized (both x and y are -9), and it's size is actually bigger than the available area.
I'm using WinAPI to get some platform specific features like Aero snap, so it becomes complicated to understand why exactly this problem happens.
My window has the following styles and attributes set:
```
setFlags(Qt::Window | Qt::FramelessWindowHint);
SetWindowLongPtr((HWND)winId(), GWL_STYLE, WS_POPUPWINDOW | WS_CAPTION | WS_SIZEBOX | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_CLIPCHILDREN);
```
```WS_CAPTION``` is same as ```WS_BORDER | WS_DLGFRAME```, so if I remove ```WS_DLGFRAME```, maximized size is ok, and I see that the native maximizing animation disappears — but I get the flickering white border when resize because of ```WS_SIZEBOX ``` (same as ```WS_THICKFRAME```). Without ```WS_SIZEBOX ``` I loose aero snap.
I thought maybe I can do something with maximixed size in ```nativeEvent```, so I tried the following:
```
bool FramelessWindow::nativeEvent(const QByteArray& eventType, void* message, qintptr* result)
{
if (auto* msg = static_cast<MSG*>(message); msg->message == WM_NCCALCSIZE)
{
NCCALCSIZE_PARAMS& params = *reinterpret_cast<NCCALCSIZE_PARAMS*>(msg->lParam);
if (params.rgrc[0].top != 0)
{
--params.rgrc[0].top;
}
*result = WVR_REDRAW;
return true; //this removes the native border and title
}
else if (msg->message == WM_GETMINMAXINFO)
{
if (IsMaximized((HWND)winId()))
{
MINMAXINFO* mmi = (MINMAXINFO*)msg->lParam;
auto g = screen()->availableGeometry();
mmi->ptMaxTrackSize.x = g.width() * devicePixelRatio();
mmi->ptMaxTrackSize.y = g.height() * devicePixelRatio();
*result = 0;
return true;
}
}
return QQuickWindow::nativeEvent(eventType, message, result);
}
```
For some reason, ```MINMAXINFO``` overloading does nothing until I set ```mmi->ptMaxTrackSize.x = g.width() * devicePixelRatio() - 1;```. In this case, the size is almost nice, except that there is a 1 px empty gap between the right border of the screen and the window. So there is no way I can obtain the correct size with changing ```MINMAXINFO```, because the real correct size should be actually same as in the above code. The initial ptMaxTrackSize is pretty strange: 3462, 1462 in ```mmi``` vs 3440, 1390 in ```availableGeometry```).
I can do something like that, but I'd like to keep QWindow::Maximized state, which is reset when I call ```setGeometry```.
```
bool FramelessWindow::eventFilter(QObject* watched, QEvent* event)
{
if (event->type() == QEvent::WindowStateChange && QWindow::visibility() == QWindow::Maximized)
{
setGeometry(screen()->availableGeometry()); //the window is no longer maximized
return true;
}
return QQuickWindow::eventFilter(watched, event);
}
```
Since I'm not able to use ```QWindow::Maximized``` in ```setGeometry``` approach, this approach equals to implementing my own maximize, normalize and so on, what is undesirable and also won't affect on maximizing with aero.
I also tried to add margins in maximized state, but creating a layout causes ugly flickering when resize, since the instance of my window is created in QML. And I'm unable to use ```setLayout``` and try to add margins in C++ code, because my class inherited ```QQuickWindow```.
Am I missing something?
**UPD:**
Now I have found out that this problem is mainly related to WinAPI + framelessness, not to Qt, so not only Qt users have "window extends beyond the screen when maximized".
It helps a bit, at least I am now able to test the already existing WinAPI solutions, but the problem is they don't work as expected.
I've tried modifying `NCCALCSIZE_PARAMS` while processing the `WM_NCCALCSIZE` message:
Here is what I got in `rgrc[0]`:
[![enter image description here][1]][1]
What I've tried according to [melak47's code][2]:
void adjustMaximized(HWND hwnd, RECT& rect)
{
auto monitor = ::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL);
if (!monitor)
{
return;
}
MONITORINFO monitor_info{};
monitor_info.cbSize = sizeof(monitor_info);
if (!::GetMonitorInfoW(monitor, &monitor_info))
{
return;
}
rect = monitor_info.rcWork;
}
bool FramelessWindow::nativeEvent(const QByteArray& eventType, void* message, qintptr* result)
{
if (auto* msg = static_cast<MSG*>(message); msg->message == WM_NCCALCSIZE)
{
NCCALCSIZE_PARAMS& params = *reinterpret_cast<NCCALCSIZE_PARAMS*>(msg->lParam);
if (params.rgrc[0].top != 0)
{
--params.rgrc[0].top;
}
if (IsMaximized(hwnd_))
{
adjustMaximized(hwnd_, params.rgrc[0]);
}
return true;
}
...
}
My top right corner becomes even worse:
[![enter image description here][3]][3]
[1]: https://i.stack.imgur.com/3mZza.png
[2]: https://stackoverflow.com/a/17713810
[3]: https://i.stack.imgur.com/59KHh.png |
|php| |
Adding my own take here because none of the answers were acceptable to me:
```kotlin
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
private fun closeChain(items: List<AutoCloseable>) {
try {
items.last().close()
} finally {
closeChain(items.dropLast(1))
}
}
class ResourceInitializationScope {
private val itemsToCloseLater = mutableListOf<AutoCloseable>()
fun closeLater(item: AutoCloseable) {
itemsToCloseLater.add(item)
}
fun closeNow() = closeChain(itemsToCloseLater)
}
/**
* Begins a block to initialize multiple resources.
*
* This is done safely. If any failure occurs, all previously-initialized resources are closed.
*
* @param block the block of code to run.
* @return an object which should be closed later to close all resources opened during the block.
*/
@OptIn(ExperimentalContracts::class)
inline fun initializingResources(block: ResourceInitializationScope.() -> Unit): AutoCloseable {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
val scope = ResourceInitializationScope()
var success = false
try {
scope.apply(block)
success = true
return AutoCloseable { scope.closeNow() }
} finally {
if (!success) scope.closeNow()
}
}
```
Example usage: (maybe don't trust the code, other than an example of how to use it, I don't trust it yet)
```kotlin
// ... omitting surrounding code ...
private val buffers: Array<AudioBuffer>
private val device: AudioDevice
private val context: AudioContext
private val source: AudioSource
private val resourcesToClose: AutoCloseable
init {
resourcesToClose = initializingResources {
buffers = Array(BUFFER_COUNT) { AudioBuffer.generate().also(::closeLater) }
device = AudioDevice.openDefaultDevice().also(::closeLater)
context = AudioContext.create(device, intArrayOf(0)).also(::closeLater)
context.makeCurrent()
device.createCapabilities()
source = AudioSource.generate()
for (i in 0 until BUFFER_COUNT) {
bufferSamples(ShortArray(0))
}
source.play()
device.detectInternalExceptions()
}
}
override fun close() {
resourcesToClose.close()
}
// ... omitting surrounding code ...
```
|
**Update:**
I raised an issue for this problem on the official Github for this azure resource `azurerm_monitor_scheduled_query_rules_alert_v2` and seems that the Contributors were helpful & have fixed this issue and the new changes will be soon rolling out in the version `3.98.0` of the azurerm provider.
The issue can be referred here for more details:
[https://github.com/hashicorp/terraform-provider-azurerm/issues/25311](https://github.com/hashicorp/terraform-provider-azurerm/issues/25311) |
Remove the partition by clause and rank
SELECT department_id, COUNT(employee_id) no_employee,
RANK() OVER (ORDER BY COUNT(employee_id) DESC ) Rank_
FROM employees
GROUP BY department_id;
https://dbfiddle.uk/d227UwOW |
Django-Cross Model Query 3 Models |
|django|django-models|django-templates| |
null |
I am trying to have duplicate repository of my source but duplicate has certain modifications that the source repo won't have. I make these modifications using clean/smudge filters. I want my smudge filter to run once per commit, i.e. if a pull contains four commits then I want the smudge filter to run four times (per commit being pulled/checkedout). This smudge filter currently runs only once per pull even if the pull contains multiple commits.
I want certain information about the commits written to a log file. My current smudge filter script looks like this:
```shell
full_commit=$(git log -1 --pretty=format:"%an|<%ae>|%ad|%H%n%B") # %n for new-line
commit_info=$(echo "$full_commit" | head -1)
commit_msg=$(echo "$full_commit" | tail -n +2)
IFS=$'|' read -r name mail dt hash <<< "$(echo $commit_info)" # get everything separated out
echo commit hash: $hash >> smudge-file.messages
echo commit author-name: $name, author-mail: $mail, commit-datetime: "$dt" >> smudge-file.messages
echo commit message: "$commit_msg" >> smudge-file.messages
echo "" >> smudge-file.messages
cat
```
Here I assume that as the smudge would run once per commit being pulled hence the `git log -1` will output the current commit's details which I append to a log file.
It makes sense that the smudge filter should run once per commit being pulled but this doesn't seem to be the case in reality as only the most recent commit information is being written to my log file.
Any help to make the smudge run per commit being checkedout is appreciated. |
Git smudge run once per checkout or per commit? |
|git|git-filter|smudge| |
On their [website](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html) on knn retrieval, they have written
> The filter is applied during the approximate kNN search to ensure that k matching documents are returned. This contrasts with a post-filtering approach, where the filter is applied after the approximate kNN search completes. Post-filtering has the downside that it sometimes returns fewer than k results, even when there are enough matching documents.
The typical way of doing attribute filtering with knn retrieval is to it before knn (attribute filtering is done first, and then vector similarity is computed through brute force) or after knn (knn retrieval is done first efficiently and then attribute filtering is done). Both of these are not perfect. The first approach is slow and the second approach has low recall.
So how does Elasticsearch do attribute filtering _during_ knn retrieval? |
How does Elasticsearch do attribute filtering during knn (vector-based) retrieval? |
|elasticsearch|knn|information-retrieval| |
Good morning,
I'm redoing a demo and I have a compilation error,I have 3 exceptions which all have a link : threw exception with message: authorizationUri cannot be empty.
```
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig' defined in file [C:\Users\chres\Documents\jetBrainProjects\intellij-idea-projects\sdia2\target\classes\com\example\sdia2\secu\SecurityConfig.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' threw exception with message: **authorizationUri cannot be empty**
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:236) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1350) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:558) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:518) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:949) ~[spring-context-6.0.16.jar:6.0.16]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:615) ~[spring-context-6.0.16.jar:6.0.16]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.1.8.jar:3.1.8]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:738) ~[spring-boot-3.1.8.jar:3.1.8]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:440) ~[spring-boot-3.1.8.jar:3.1.8]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-3.1.8.jar:3.1.8]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-3.1.8.jar:3.1.8]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-3.1.8.jar:3.1.8]
at com.example.sdia2.Sdia2Application.main(Sdia2Application.java:15) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:50) ~[spring-boot-devtools-3.1.8.jar:3.1.8]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' **threw exception with message: authorizationUri cannot be empty**
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1330) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:558) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:518) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1417) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1337) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:906) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:784) ~[spring-beans-6.0.16.jar:6.0.16]
... 22 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method **'clientRegistrationRepository' threw exception with message: authorizationUri cannot be empty**
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.0.16.jar:6.0.16]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:646) ~[spring-beans-6.0.16.jar:6.0.16]
... 36 common frames omitted
Caused by: java.lang.IllegalArgumentException: **authorizationUri cannot be empty**
at org.springframework.util.Assert.hasText(Assert.java:294) ~[spring-core-6.0.16.jar:6.0.16]
at org.springframework.security.oauth2.client.registration.ClientRegistration$Builder.validateAuthorizationCodeGrantType(ClientRegistration.java:660) ~[spring-security-oauth2-client-6.1.6.jar:6.1.6]
at org.springframework.security.oauth2.client.registration.ClientRegistration$Builder.build(ClientRegistration.java:610) ~[spring-security-oauth2-client-6.1.6.jar:6.1.6]
at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesMapper.getClientRegistration(OAuth2ClientPropertiesMapper.java:87) ~[spring-boot-autoconfigure-3.1.8.jar:3.1.8]
at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesMapper.lambda$asClientRegistrations$0(OAuth2ClientPropertiesMapper.java:65) ~[spring-boot-autoconfigure-3.1.8.jar:3.1.8]
at java.base/java.util.HashMap.forEach(HashMap.java:1429) ~[na:na]
at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesMapper.asClientRegistrations(OAuth2ClientPropertiesMapper.java:64) ~[spring-boot-autoconfigure-3.1.8.jar:3.1.8]
at org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientRegistrationRepositoryConfiguration.clientRegistrationRepository(OAuth2ClientRegistrationRepositoryConfiguration.java:49) ~[spring-boot-autoconfigure-3.1.8.jar:3.1.8]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139) ~[spring-beans-6.0.16.jar:6.0.16]
... 37 common frames omitted
```
application.properties
```properties
spring.application.name=customer-app
server.port=8084
spring.security.oauth2.client.registration.google.client-id=290479700275-7t9jjpd5agua1u7n881fubvd2ceqg7aq.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=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
spring.security.oauth2.client.provider.github.user-name-attribute=login
spring.security.oauth2.client.registration.github.client-id=Iv1.3369f41e3d67c0a3
spring.security.oauth2.client.registration.github.client-secret=f7cb85296f581390511d1bf4aa29bcc43af7b163
spring.security.oauth2.client.provider.google.user-name-attribute=email
spring.datasource.url=jdbc:h2:mem:customers-db
spring.h2.console.enabled=true
spring.security.oauth2.client.registration.keycloak.client-name=keycloak
spring.security.oauth2.client.registration.keycloak.client-id=client-cree-customer
spring.security.oauth2.client.registration.keycloak.client-secret=C6JJFHCOkDSvaZwLAy673yHVnXkDu6k3
spring.security.oauth2.client.registration.keycloak.scope=openid, profile, email, offline_access
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.redirect-uri=http://localhost:8084/login/oauth2/code/sdia3
spring.security.oauth2.client.registration.keycloak.issuer-uri=http://localhost:8080/realms/sdia3/account
spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username
```
```java
@Controller
public class CustomerController {
/**
* acces a interface
*/
private CustomerRepository customerRepository;
public CustomerController(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@GetMapping("/customers")
@PreAuthorize("hasAuthority('ADMIN')")
public String customers(Model model){
List<Customer> customersList = customerRepository.findAll();
model.addAttribute("customers", customersList);
return "customers";
}
@GetMapping("/products")
public String products(Model model){
return "products";
}
@GetMapping("/auth")
@ResponseBody//vu que ce n'est pas un rest controller, il doit y avoir cette anotation pour retourner la reponse sous format json
public Authentication auth(Authentication authentication){
return authentication;
}
@GetMapping("/")
public String index(){
return "index";
}
}
```
pom
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>sdia2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sdia2</name>
<description>sdia2</description>
<properties>
<java.version>21</java.version>
</properties>
<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-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity6 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.shared/maven-dependency-tree -->
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-dependency-tree</artifactId>
<version>3.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-messaging -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
<version>6.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.3.2</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.11.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
SecurityConfig
```java
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
//stock les diff providers conf dans l'appli pour la connection clients
private final ClientRegistrationRepository clientRegistrationRepository;
//inj de dependance via constructeur
public SecurityConfig(ClientRegistrationRepository clientRegistrationRepository){
this.clientRegistrationRepository=clientRegistrationRepository;
}
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(Customizer.withDefaults())//config par def.
.authorizeHttpRequests(ar-> ar.anyRequest().authenticated())//toutes requetes necessite une authentification
.authorizeHttpRequests(ar->ar.requestMatchers("/","/webjars/**","/h2-console/**").permitAll())//toute url sans besoin de s'authentifier:parefeu
.oauth2Login(Customizer.withDefaults())
.logout((logout)->logout
.logoutSuccessHandler(oidcLogoutSuccessHandler())
.logoutSuccessUrl("/").permitAll()
.clearAuthentication(true)
.deleteCookies("JSESSIONID"));
return http.build();
}
private OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler() {
final OidcClientInitiatedLogoutSuccessHandler oidcClientInitiatedLogoutSuccessHandler=
new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);
oidcClientInitiatedLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}?logoutsuccess=true");
return oidcClientInitiatedLogoutSuccessHandler;
}
}
```
Main
```java
@SpringBootApplication
public class Sdia2Application {
public static void main(String[] args) {
SpringApplication.run(Sdia2Application.class, args);
}
//s'execute au demarrage=onInit() avec en para l'int customerrepository pour utiliser ses methodes REST=inj dep
@Bean
CommandLineRunner commandLineRunner(CustomerRepository customerRepository) {
return args -> {
customerRepository.save(Customer.builder().name("casfr").email("ch@fr.fr").build());
customerRepository.save(Customer.builder().name("chrissdf").email("c9@s.fr").build());
customerRepository.save(Customer.builder().name("lor").email("c36@fr.fr").build());
};
}
}
```
CustomerRepository
```java
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
```
I clearly defined this in my property file:
```properties
spring.security.oauth2.client.registration.keycloak.redirect-uri=http://localhost:8084/login/oauth2/code/sdia3
spring.security.oauth2.client.registration.keycloak.issuer-uri=http://localhost:8080/realms/sdia3/account
```
is this not enough?
|
If the same network meta-analysis object is used for arguments x and y, reciprocal treatment estimates will be shown in the upper triangle
https://search.r-project.org/CRAN/refmans/netmeta/html/netleague.html
I really cannot understand and I wanna show reciprocal treatment estimates in the upper triangle |
I have the following very simple page
```
<!DOCTYPE html>
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
div {height : 1500px}
</style>
</head>
<body>
<div id="top" style='background-color: #ec8686;' >
<h1>TOP DIV</h1>
</div>
<div id="middle" style='background-color: #95eb95;' >
<h1>MIDDLE DIV</h1>
<input type="button" value="Hide Top" onclick="document.getElementById('top').remove();">
<input type="button" value="Hide Bottom" onclick="document.getElementById('bottom').remove();">
</div>
<div id="bottom" style='background-color: #a9a9f5;' >
<h1>BOTTOM DIV</h1>
</div>
</body>
</html>
```
On desktop, if I click on "hide top" or "hide bottom", the scroll bar is automatically adjusted by the browser such that the buttons remain in view as expected by the scroll anchoring feature.
On mobile however (Chrome and Safari iOS), only "Hide Bottom" maintains scroll anchoring. "Hide Top" causes content jumps.
Why is that? Is this a bug in mobile implementation? Any proper fix? I am trying to keep the buttons in view and avoid jumps regardless whether content is added or removed at the top or bottom.
This is JSFIDDLE for your convenience. Try it on mobile to see the issue.
<https://jsfiddle.net/zb31a9m0/>
|
Understanding Scroll Anchoring Behavoir |
|javascript|html|css|scroll|infinite-scroll| |
My flutter version 3.19. I use `chewie: ^1.7.5 `and `video_player: ^2.8.3` for playing a video in FlutteBut, the Android emulator shows meaningless video images on the phone screen.
When I opened the page of the video, it played but didn't look expected butterfly video and not heard sound of it.
Emulator shows / Expected
[](https://i.stack.imgur.com/VveWC.png)
My video player screen dart file codes:
```
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class VideoScreen extends StatefulWidget {
const VideoScreen({super.key});
@override
State<VideoScreen> createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Video Player"),
),
body: const PlayerWidget(),
);
}
}
//----------PLAYER WIDGET SECTION
class PlayerWidget extends StatefulWidget {
const PlayerWidget({super.key});
@override
State<PlayerWidget> createState() => _PlayerWidgetState();
}
class _PlayerWidgetState extends State<PlayerWidget> {
late VideoPlayerController videoPlayerController;
late ChewieController chewieController;
bool isVideoInialized = false;
Future initilizeVideo() async {
videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'));
await videoPlayerController.initialize();
chewieController = ChewieController(
videoPlayerController: videoPlayerController,
autoPlay: true,
looping: true);
videoPlayerController.initialize().then((_) => setState(() {
isVideoInialized = true;
}));
}
@override
void initState() {
super.initState();
// videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(
// 'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'));
// chewieController = ChewieController(
// videoPlayerController: videoPlayerController,
// autoPlay: true,
// looping: true);
// videoPlayerController.initialize().then((_) => setState(() {
// isVideoInialized = true;
// }));
initilizeVideo();
}
@override
Widget build(BuildContext context) {
if (isVideoInialized) {
return AspectRatio(
aspectRatio: videoPlayerController.value.aspectRatio,
child: Chewie(controller: chewieController),
);
} else {
return const CircularProgressIndicator();
}
}
@override
void dispose() {
videoPlayerController.dispose();
chewieController.dispose();
super.dispose();
}
}
```
UPDATED INFORMATION:
It looks like the emulator has a problem.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/njPzU.jpg |
The proper `fish` version of that loop is:
```
for i in *.cue; chdman createcd -i $i -o (path change-extension chd $i); end
```
`fish` is *not* a Bourne-style shell like `sh` or `bash` or `zsh` and does not have the same syntax. Trying to treat it like it is in that family is of course not going work very well. You should read through its documentation if you're planning on using it for scripting. I'd start with [`fish` for `bash` users](https://fishshell.com/docs/current/fish_for_bash_users.html). |
{"Voters":[{"Id":1255289,"DisplayName":"miken32"},{"Id":17562044,"DisplayName":"Sunderam Dubey"},{"Id":16217248,"DisplayName":"CPlus"}],"SiteSpecificCloseReasonIds":[11]} |
I've downloaded **SFML-2.6.1** and created Xcode project from template on my **M1 Mac**. Although project is building, it can not run, raising this error in the **Xcode** terminal:
```
dyld[7793]: Library not loaded: @rpath/sfml-system.framework/Versions/2.6.1/sfml-system
Referenced from: <1E3396AD-BA26-30F7-9B22-99E9329A24A5> /Users/zolars/Library/
Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/Build/Products/Debug/RayMarching.app/Contents/MacOS/RayMarching
Reason: tried: '/Users/zolars/Library/Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/
Build/Products/Debug/sfml-system.framework/Versions/2.6.1/sfml-system' (no such file),
'/Users/zolars/Library/Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/
Build/Products/Debug/RayMarching.app/Contents/MacOS/../Frameworks/sfml-system.framework/Versions/2.6.1/sfml-system' (no such file),
'/Users/zolars/Library/Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/
Build/Products/Debug/RayMarching.app/Contents/MacOS/../Frameworks/sfml-system.framework/Versions/2.6.1/sfml-system' (no such file)
```
I searched internet about similar errors but without any luck so far.
Can anybody help me? |
The data structure for this is a Trie (Prefix Tree):
```php
<?php
class TrieNode {
public $childNode = []; // Associative array to store child nodes
public $endOfString = false; // Flag to indicate end of a string
}
class Trie {
private $root;
public function __construct() {
$this->root = new TrieNode();
}
public function insert($string) {
if (!empty($string)) {
$this->insertRecursive($this->root, $string);
}
}
private function insertRecursive(&$node, $string) {
if (empty($string)) {
$node->endOfString = true;
return;
}
$firstChar = $string[0];
$remainingString = substr($string, 1);
if (!isset($node->childNode[$firstChar])) {
$node->childNode[$firstChar] = new TrieNode();
}
$this->insertRecursive($node->childNode[$firstChar], $remainingString);
}
public function commonPrefix() {
$commonPrefix = '';
$this->commonPrefixRecursive($this->root, $commonPrefix);
return $commonPrefix;
}
private function commonPrefixRecursive($node, &$commonPrefix) {
if (count($node->childNode) !== 1 || $node->endOfString) {
return;
}
$firstChar = array_key_first($node->childNode);
$commonPrefix .= $firstChar;
$this->commonPrefixRecursive($node->childNode[$firstChar], $commonPrefix);
}
}
// Example usage
$trie = new Trie();
$trie->insert("/home/texai/www/app/application/cron/logCron.log");
$trie->insert("/home/texai/www/app/application/jobs/logCron.log");
$trie->insert("/home/texai/www/app/var/log/application.log");
$trie->insert("/home/texai/www/app/public/imagick.log");
$trie->insert("/home/texai/www/app/public/status.log");
echo "Common prefix: " . $trie->commonPrefix() . PHP_EOL;
?>
```
|
Second code: <br>
It doesn't work because it attempts to send and receive on the channel within the same main function, without goroutines. <br>
Reason: The `for i := 0; i < cap(c); i++` loop starts sending values to the channel. When it sends the first value, it blocks, waiting for a receiver. The subsequent `for i := range c` loop is supposed to receive those values, but it never gets a chance to start because the first loop is already blocked. This creates a circular dependency where each operation blocks the other, leading to the deadlock and the "goroutine 1 [chan receive]: main.main() /path exit status 2" error.
The first code works because it leverages goroutines to run the sending and receiving operations concurrently. The `go inserChannel(c)` line launches a new goroutine that executes the inserChannel function independently. This goroutine starts sending values to the channel, allowing the main function to proceed to the `for i := range c` loop to receive them. |
assumming that we wish to access the `job_id` within the job/command code: know that there's a much simpler way, just use `os.getenv("AZUREML_RUN_ID")` to get the RUN_ID
|
I'm hoping someone can help me get these two checkboxes with text side by side instead of top / bottom.
Thanks!
https://jsfiddle.net/j8y1x7q9/
<div class="checkbox-wrapper-33">
<label class="checkbox">
<input class="checkbox__trigger visuallyhidden" name="WAV" type="checkbox" checked />
<span class="checkbox__symbol">
<svg aria-hidden="true" class="icon-checkbox" width="28px" height="28px" viewBox="0 0 28 28" version="1" xmlns="http://www.w3.org/2000/svg">
<path d="M4 14l8 7L24 7"></path>
</svg>
</span>
<p class="checkbox__textwrapper">WAV</p>
</label>
<label class="checkbox">
<input class="checkbox__trigger visuallyhidden" name="MP3" type="checkbox" />
<span class="checkbox__symbol">
<svg aria-hidden="true" class="icon-checkbox" width="28px" height="28px" viewBox="0 0 28 28" version="1" xmlns="http://www.w3.org/2000/svg">
<path d="M4 14l8 7L24 7"></path>
</svg>
</span>
<p class="checkbox__textwrapper">MP3</p>
</label>
</div> |