CREATE TABLE visits (
visit_id INT,
emp_id INT,
time_in DATETIME,
timeout DATETIME,
duration INT
);
INSERT INTO visits (visit_id, emp_id, time_in, timeout, duration)
VALUES
(15, 2, '2012-03-14 09:30:00', '2012-03-14 10:30:00', 60),
(16, 2, '2012-03-14 10:00:00', '2012-03-14 11:00:00', 60),
(18, 2, '2012-03-14 10:00:00', '2012-03-14 11:00:00', 60),
(25, 2, '2012-03-14 10:00:00', '2012-03-14 11:00:00', 60),
(30, 5, '2012-05-16 13:00:00', '2012-05-16 14:30:00', 90),
(33, 5, '2012-05-16 13:30:00', '2012-05-16 15:30:00', 120);
---
Query #1
select
emp_id,
time_in,
timeout,
duration,
visit_id,
rank () over (partition by emp_id,time_in order by timeout desc, visit_id asc) rank
from visits;
emp_id
time_in
timeout
duration
visit_id
rank
2
2012-03-14 09:30:00
2012-03-14 10:30:00
60
15
1
2
2012-03-14 10:00:00
2012-03-14 11:00:00
60
16
1
2
2012-03-14 10:00:00
2012-03-14 11:00:00
60
18
2
2
2012-03-14 10:00:00
2012-03-14 11:00:00
60
25
3
5
2012-05-16 13:00:00
2012-05-16 14:30:00
90
30
1
5
2012-05-16 13:30:00
2012-05-16 15:30:00
120
33
1
---
View on DB Fiddle
Ideally, I want to group all emp_id = 2 visits together and extract highest duration which we see is 60 but the first row has been separated from the others under emp_id = 2. Same for emp_id = 5, which would be 120 for duration but it's saying 90 and 120. Is this where 'gap and island' come into play or is there an alternative?
Thanks
Pages
▼
31 July, 2024
How to find intersection of two ActiveRecord query results in Rails?
I am working on a Ruby on Rails project where I need to find records in a database that satisfy two different conditions on the same column.
The issue arose when I wanted to find patients who satisfy both of the following conditions. When I put the query into Ransack like this:
queries = {"groupings" => {
"0" => {
"c" => {
"0" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "1234" } }
},
"1" => {
"a" => { "0" => { "name" => "disease_type" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
"2" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "4567" } }
},
"3" => {
"a" => { "0" => { "name" => "flag" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
}
}
}
patient.ransack(queries).result.to_sql
This is what gets returned:
select *
from patients p
join patient_diseases pd
on p.id = pd.patient_id
where pd.disease_code in 1234
and pd.disease_type = 1
and pd.disease_code in (4567)
and pd.flag in (1)
but I want SQL like this
select *
from patients p
join patient_diseases pd1
on p.id = pd1.patient_id
where pd1.disease_code = 1234
and pd1.disease_type = 1
and exists (
select 1
from patient_diseases pd2
where pd2.patient_id = p.id
and pd2.disease_code = 4567
and pd2.flag = 1
);
Instead, I am considering fetching the results for each condition separately and then finding the intersection of these results in the backend.
For example, I have a Patient model and I want to find patients that satisfy condition_1 and condition_2.
# Patients satisfying condition_1
patients_condition_1 = Patient.where(condition_1)
# Patients satisfying condition_2
patients_condition_2 = Patient.where(condition_2)
# Intersection of both conditions
intersecting_patients = patients_condition_1 & patients_condition_2
Is this a good approach, or is there a better way to achieve this in Rails? Any suggestions or improvements are highly appreciated!
PS: I know I could subquery but, there is so many different condition to find it.
So, I give up using a subquery.
The issue arose when I wanted to find patients who satisfy both of the following conditions. When I put the query into Ransack like this:
queries = {"groupings" => {
"0" => {
"c" => {
"0" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "1234" } }
},
"1" => {
"a" => { "0" => { "name" => "disease_type" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
"2" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "4567" } }
},
"3" => {
"a" => { "0" => { "name" => "flag" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
}
}
}
patient.ransack(queries).result.to_sql
This is what gets returned:
select *
from patients p
join patient_diseases pd
on p.id = pd.patient_id
where pd.disease_code in 1234
and pd.disease_type = 1
and pd.disease_code in (4567)
and pd.flag in (1)
but I want SQL like this
select *
from patients p
join patient_diseases pd1
on p.id = pd1.patient_id
where pd1.disease_code = 1234
and pd1.disease_type = 1
and exists (
select 1
from patient_diseases pd2
where pd2.patient_id = p.id
and pd2.disease_code = 4567
and pd2.flag = 1
);
Instead, I am considering fetching the results for each condition separately and then finding the intersection of these results in the backend.
For example, I have a Patient model and I want to find patients that satisfy condition_1 and condition_2.
# Patients satisfying condition_1
patients_condition_1 = Patient.where(condition_1)
# Patients satisfying condition_2
patients_condition_2 = Patient.where(condition_2)
# Intersection of both conditions
intersecting_patients = patients_condition_1 & patients_condition_2
Is this a good approach, or is there a better way to achieve this in Rails? Any suggestions or improvements are highly appreciated!
PS: I know I could subquery but, there is so many different condition to find it.
So, I give up using a subquery.
Postgres CTE value not being used in where clause
I'm trying to run this query that updates an ordering column after inserting the rows, and everything seems to work fine except using the id FROM the CTE query in the WHERE clause doesn't work, even though it works everywhere else. This is the query
WITH variant AS (
INSERT INTO accessory_variants (
accessory_id,
label,
multiple
) VALUES (
1,
'Colors',
FALSE
) RETURNING *
),
opts AS (
INSERT INTO accessory_variant_options (
accessory_id,
accessory_variant_id,
price,
label,
description
) VALUES (
1,
(SELECT id FROM variant),
100,
'Red',
'A red one'
),
(
1,
(SELECT id FROM variant),
100,
'Blue',
'A blue one'
) RETURNING id
),
ids AS (
SELECT JSONB_AGG(id) AS option_ids FROM opts
)
UPDATE
accessory_variants
SET
ordering = ids.option_ids
FROM
variant,
ids
WHERE
accessory_variants.id = variant.id
Where it gets weird is if I change it to something like this
...
UPDATE
accessory_variants
SET
ordering = TO_JSONB(variant.id)
FROM
variant,
ids
WHERE
accessory_variants.id = {existing row id}
The ordering table is populated with the correct id, so variant.id contains the correct id, but still can't be found by the where clause
WITH variant AS (
INSERT INTO accessory_variants (
accessory_id,
label,
multiple
) VALUES (
1,
'Colors',
FALSE
) RETURNING *
),
opts AS (
INSERT INTO accessory_variant_options (
accessory_id,
accessory_variant_id,
price,
label,
description
) VALUES (
1,
(SELECT id FROM variant),
100,
'Red',
'A red one'
),
(
1,
(SELECT id FROM variant),
100,
'Blue',
'A blue one'
) RETURNING id
),
ids AS (
SELECT JSONB_AGG(id) AS option_ids FROM opts
)
UPDATE
accessory_variants
SET
ordering = ids.option_ids
FROM
variant,
ids
WHERE
accessory_variants.id = variant.id
Where it gets weird is if I change it to something like this
...
UPDATE
accessory_variants
SET
ordering = TO_JSONB(variant.id)
FROM
variant,
ids
WHERE
accessory_variants.id = {existing row id}
The ordering table is populated with the correct id, so variant.id contains the correct id, but still can't be found by the where clause
zip the files and folders inside a parent directory without including the parent directory + Amazon Linux
Is there a Linux command to zip the files and folders inside a parent directory without including the parent directory.
From all the solutions that I tried, the parent directory also is getting zipped
From all the solutions that I tried, the parent directory also is getting zipped
Multiply polars columns of number type with object type (which supports __mul__)
I have the following code:
import polars as pl
class Summary:
def __init__(self, value: float, origin: str):
self.value = value
self.origin = origin
def __repr__(self) -> str:
return f'Summary({self.value},{self.origin})'
def __mul__(self, x: float | int) -> 'Summary':
return Summary(self.value * x, self.origin)
def __rmul__(self, x: float | int) -> 'Summary':
return self * x
mapping = {
'CASH': Summary( 1, 'E'),
'ITEM': Summary(-9, 'A'),
'CHECK': Summary(46, 'A'),
}
df = pl.DataFrame({'quantity': [7, 4, 10], 'type': mapping.keys(), 'summary': mapping.values()})
Variable df looks like this
shape: (3, 3)
┌──────────┬───────┬───────────────┐
│ quantity ┆ type ┆ summary │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ object │
╞══════════╪═══════╪═══════════════╡
│ 7 ┆ CASH ┆ Summary(1,E) │
│ 4 ┆ ITEM ┆ Summary(-9,A) │
│ 10 ┆ CHECK ┆ Summary(46,A) │
└──────────┴───────┴───────────────┘
So the summary column contains a Summary class object, which supports multiplication. I now want to multiply this column with the quantity column. However
df.with_columns(pl.col('quantity').mul(pl.col('summary')).alias('qty_summary'))
is failing with SchemaError: failed to determine supertype of i64 and object.
Is there a way to multiply these columns?
import polars as pl
class Summary:
def __init__(self, value: float, origin: str):
self.value = value
self.origin = origin
def __repr__(self) -> str:
return f'Summary({self.value},{self.origin})'
def __mul__(self, x: float | int) -> 'Summary':
return Summary(self.value * x, self.origin)
def __rmul__(self, x: float | int) -> 'Summary':
return self * x
mapping = {
'CASH': Summary( 1, 'E'),
'ITEM': Summary(-9, 'A'),
'CHECK': Summary(46, 'A'),
}
df = pl.DataFrame({'quantity': [7, 4, 10], 'type': mapping.keys(), 'summary': mapping.values()})
Variable df looks like this
shape: (3, 3)
┌──────────┬───────┬───────────────┐
│ quantity ┆ type ┆ summary │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ object │
╞══════════╪═══════╪═══════════════╡
│ 7 ┆ CASH ┆ Summary(1,E) │
│ 4 ┆ ITEM ┆ Summary(-9,A) │
│ 10 ┆ CHECK ┆ Summary(46,A) │
└──────────┴───────┴───────────────┘
So the summary column contains a Summary class object, which supports multiplication. I now want to multiply this column with the quantity column. However
df.with_columns(pl.col('quantity').mul(pl.col('summary')).alias('qty_summary'))
is failing with SchemaError: failed to determine supertype of i64 and object.
Is there a way to multiply these columns?
30 July, 2024
React's useState hook defined inside function component in TypeScript still gave error - Invalid hook call
I was building a custom react component library. When I started using useState hook for a hover feature implementation. I started getting the following error in the browser console from the app generated by create-react-app.
Been trying to figure out the bug for quite some time, but haven't been able to fix this. Everywhere on stackoverflow and other troubleshooting articles told about defining the hooks in the top level of a function component, and according to my belief, I have defined it inside the top of function component in typescript.
Still the error happens.
Error from browser console
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
* You might have mismatching versions of React and the renderer (such as React DOM)
* You might be breaking the Rules of Hooks
* You might have more than one copy of React in the same app
See
https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
What I tried
* const [hover, setHover] = useState(false); is actually defined in the top of a function component
* I have removed react, react-dom and their types @types/react, @types/react-dom and readded them of the version v18.3.0 both in the library & the app
* Ran npm ls react inside the app & found extraneous tagged react from the library, so ran npm prune
* Tested on browser firefox & edge
* Extracted a minimal component (button) from the library and redid a minimal version of the whole library and app implementation, figured the error comes only when adding the useState hook.
* Removed react in the generated app from create-react-app using yarn remove react command and just used the react which was included in the library. Had to run npm prune & also delete package-lock.json. Still it was an invalid hook implementation
Library
Just below is the code from react custom component library
(./jaghu/src/components/Button/Button.tsx)
import React, { useState } from "react";
export interface IButtonProps
extends React.DetailedHTMLProps<
React.ButtonHTMLAttributes,
HTMLButtonElement
> {
backgroundColor?: string;
color?: string;
width?: string;
height?: string;
}
export const Button: React.FunctionComponent = (props) => {
const [hover, setHover] = useState(false);
const MouseOver = () => setHover(true);
const MouseOut = () => setHover(false);
const { backgroundColor, width, height } = props;
let _style: React.CSSProperties = {
width: width ? width : "200px",
height: height ? height : "100px",
backgroundColor: backgroundColor ? backgroundColor : "skyblue",
color: hover ? "black" : "red",
};
/** Override Defaults CSS data using the values in Props CSS */
if (backgroundColor) _style.backgroundColor = backgroundColor;
if (width) _style.width = width;
if (height) _style.height = height;
return (
Hello BuTToNo
);
};
Library's package.json
(./jaghu/package.json)
{
"name": "jaghu",
"version": "1.0.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.0.0",
"@types/react": "18.3.0",
"@types/react-dom": "18.3.0",
"@types/react-helmet": "^6.1.11",
"prettier": "^3.3.3",
"react": "18.3.0",
"react-dom": "18.3.0",
"react-helmet": "^6.1.0",
"typescript": "^5.5.4"
},
"scripts": {
"build": "rm -rf dist/ && prettier --write src/ && yarn run build:esm && yarn run build:cjs",
"build:esm": "tsc",
"build:cjs": "tsc --module CommonJS --outDir dist/cjs"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"dependencies": {}
}
App
Just below is the code inside an app created by create-react-app
(./app/src/App.js)
import {Button} from 'jaghu';
function App() {
return (
);
}
export default App;
Code inside the create-react-app generated app's package.json
(./app/package.json)
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"react-dom": "18.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"jaghu": "../jaghu"
}
}
Been trying to figure out the bug for quite some time, but haven't been able to fix this. Everywhere on stackoverflow and other troubleshooting articles told about defining the hooks in the top level of a function component, and according to my belief, I have defined it inside the top of function component in typescript.
Still the error happens.
Error from browser console
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
* You might have mismatching versions of React and the renderer (such as React DOM)
* You might be breaking the Rules of Hooks
* You might have more than one copy of React in the same app
See
https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
What I tried
* const [hover, setHover] = useState(false); is actually defined in the top of a function component
* I have removed react, react-dom and their types @types/react, @types/react-dom and readded them of the version v18.3.0 both in the library & the app
* Ran npm ls react inside the app & found extraneous tagged react from the library, so ran npm prune
* Tested on browser firefox & edge
* Extracted a minimal component (button) from the library and redid a minimal version of the whole library and app implementation, figured the error comes only when adding the useState hook.
* Removed react in the generated app from create-react-app using yarn remove react command and just used the react which was included in the library. Had to run npm prune & also delete package-lock.json. Still it was an invalid hook implementation
Library
Just below is the code from react custom component library
(./jaghu/src/components/Button/Button.tsx)
import React, { useState } from "react";
export interface IButtonProps
extends React.DetailedHTMLProps<
React.ButtonHTMLAttributes,
HTMLButtonElement
> {
backgroundColor?: string;
color?: string;
width?: string;
height?: string;
}
export const Button: React.FunctionComponent = (props) => {
const [hover, setHover] = useState(false);
const MouseOver = () => setHover(true);
const MouseOut = () => setHover(false);
const { backgroundColor, width, height } = props;
let _style: React.CSSProperties = {
width: width ? width : "200px",
height: height ? height : "100px",
backgroundColor: backgroundColor ? backgroundColor : "skyblue",
color: hover ? "black" : "red",
};
/** Override Defaults CSS data using the values in Props CSS */
if (backgroundColor) _style.backgroundColor = backgroundColor;
if (width) _style.width = width;
if (height) _style.height = height;
return (
Hello BuTToNo
);
};
Library's package.json
(./jaghu/package.json)
{
"name": "jaghu",
"version": "1.0.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.0.0",
"@types/react": "18.3.0",
"@types/react-dom": "18.3.0",
"@types/react-helmet": "^6.1.11",
"prettier": "^3.3.3",
"react": "18.3.0",
"react-dom": "18.3.0",
"react-helmet": "^6.1.0",
"typescript": "^5.5.4"
},
"scripts": {
"build": "rm -rf dist/ && prettier --write src/ && yarn run build:esm && yarn run build:cjs",
"build:esm": "tsc",
"build:cjs": "tsc --module CommonJS --outDir dist/cjs"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"dependencies": {}
}
App
Just below is the code inside an app created by create-react-app
(./app/src/App.js)
import {Button} from 'jaghu';
function App() {
return (
);
}
export default App;
Code inside the create-react-app generated app's package.json
(./app/package.json)
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"react-dom": "18.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"jaghu": "../jaghu"
}
}
Group by case where col A & col B = col B & col A, and then mutate column based on within-group similarity
I'm using R to format some data for a social network diagram that I'm visualizing in another program, and I'm looking for a way to designate whether edges are asymmetric or symmetric.
I've got data that look like this:
source target weight
1 C D 2
2 F E 0
3 G H 1
4 B A 2
5 H G 1
6 A B 2
7 E F 0
8 D C 2
9 J I 1
10 P O 4
11 M N 3
12 K L 0
13 N M 4
14 O P 1
15 I J 3
16 L K 2
I want to use dplyr to create a column "symmetry" where for every pair of columns in which the source and target of one row equal the target and source of a different row, it assesses whether the "weight" column is equal. If it is equal, the column "symmetry" should read "symmetrical", and if they are not equal, it should read "asymmetrical".
This is the output I want:
source target weight symmetry
1 C D 2 Symmetrical
2 F E 0 Symmetrical
3 G H 1 Symmetrical
4 B A 2 Symmetrical
5 H G 1 Symmetrical
6 A B 2 Symmetrical
7 E F 0 Symmetrical
8 D C 2 Symmetrical
9 J I 1 Asymmetrical
10 P O 4 Asymmetrical
11 M N 3 Asymmetrical
12 K L 0 Asymmetrical
13 N M 4 Asymmetrical
14 O P 1 Asymmetrical
15 I J 3 Asymmetrical
16 L K 2 Asymmetrical
I tried this:
df%
group_by(source=pmin(source,target),target=pmax(source,target)) %>%
mutate(symmetry=ifelse(n_distinct(weight)==1,"Symmetrical","Asymmetrical")) %>%
ungroup()
but found that when I looked at the resulting dataframe, there were a bunch of cases in which source==target, which should not be the case for any row. I'm struggling with both the group_by syntax and the mutate syntax.
My preference is to use dplyr for this task, but would welcome ideas using any other R packages as well! Thank you!
I've got data that look like this:
source target weight
1 C D 2
2 F E 0
3 G H 1
4 B A 2
5 H G 1
6 A B 2
7 E F 0
8 D C 2
9 J I 1
10 P O 4
11 M N 3
12 K L 0
13 N M 4
14 O P 1
15 I J 3
16 L K 2
I want to use dplyr to create a column "symmetry" where for every pair of columns in which the source and target of one row equal the target and source of a different row, it assesses whether the "weight" column is equal. If it is equal, the column "symmetry" should read "symmetrical", and if they are not equal, it should read "asymmetrical".
This is the output I want:
source target weight symmetry
1 C D 2 Symmetrical
2 F E 0 Symmetrical
3 G H 1 Symmetrical
4 B A 2 Symmetrical
5 H G 1 Symmetrical
6 A B 2 Symmetrical
7 E F 0 Symmetrical
8 D C 2 Symmetrical
9 J I 1 Asymmetrical
10 P O 4 Asymmetrical
11 M N 3 Asymmetrical
12 K L 0 Asymmetrical
13 N M 4 Asymmetrical
14 O P 1 Asymmetrical
15 I J 3 Asymmetrical
16 L K 2 Asymmetrical
I tried this:
df%
group_by(source=pmin(source,target),target=pmax(source,target)) %>%
mutate(symmetry=ifelse(n_distinct(weight)==1,"Symmetrical","Asymmetrical")) %>%
ungroup()
but found that when I looked at the resulting dataframe, there were a bunch of cases in which source==target, which should not be the case for any row. I'm struggling with both the group_by syntax and the mutate syntax.
My preference is to use dplyr for this task, but would welcome ideas using any other R packages as well! Thank you!
Append dict to Chainmap during loop
I have a loop that creates a dictionary based on a directory.
I like to save the results in a json with some other data, and I want them to be chained.
The loop is in a function, which is called upon in the final dict which will become the json.
The best structure I have found for this is a Chainmap, but I can't seem to update, add or append to it.
Is there a way I can do this?
Or do I have to save the dictionaries in a list and then add more code to remove the "[" and "]" in my final dict?
The loop for the chainmap looks like this:
for root, subfolders, filenames in os.walk(path):
for filename in filenames:
try:
entry = {
"name": "#" + filename
#more data
}
#append the entry to chainmap?
except:
raise
I like to save the results in a json with some other data, and I want them to be chained.
The loop is in a function, which is called upon in the final dict which will become the json.
The best structure I have found for this is a Chainmap, but I can't seem to update, add or append to it.
Is there a way I can do this?
Or do I have to save the dictionaries in a list and then add more code to remove the "[" and "]" in my final dict?
The loop for the chainmap looks like this:
for root, subfolders, filenames in os.walk(path):
for filename in filenames:
try:
entry = {
"name": "#" + filename
#more data
}
#append the entry to chainmap?
except:
raise
What is the best VSCode extension for Testing in Laravel?
Hi. I would love do tests with some test explorer UI.
I tried with Better PHP Unit extension. It works well at start. But it fails on refreshing tests when I modify code. If there is exception is not clear where it is. And refreshing test in left windows don't work. I must restart VSCode and simetimes it continue working.
I am trying now PHPUnit Test EXplorer extension, but I dont' know of how can configure it for working with php artisan test command.
How do you test in laravel in VSCode? submitted by /u/Pigmalion_Tseyor
[link] [comments]
I tried with Better PHP Unit extension. It works well at start. But it fails on refreshing tests when I modify code. If there is exception is not clear where it is. And refreshing test in left windows don't work. I must restart VSCode and simetimes it continue working.
I am trying now PHPUnit Test EXplorer extension, but I dont' know of how can configure it for working with php artisan test command.
How do you test in laravel in VSCode? submitted by /u/Pigmalion_Tseyor
[link] [comments]
29 July, 2024
Deploy the laravel application in under 120 seconds using deployer
Deployment is one of the messiest things if not done correctly. This can cause downtime which in turn can cause significant damage to businesses. There are so many checks to make sure all goes well. And even after that sometimes shit happens. Not anymore...
https://www.youtube.com/watch?v=8YKLsAAdz5Y submitted by /u/samgan-khan
[link] [comments]
https://www.youtube.com/watch?v=8YKLsAAdz5Y submitted by /u/samgan-khan
[link] [comments]
Has anyone used Turbolinks + Laravel to create a native hybrid app?
I really want a simple iOS app for my Laravel project, but I’m not seeing very many recent posts / tutorials/ etc about Turbolinks and Laravel.
Has Turbolinks pretty much become exclusive to Ruby on Rails? Anyone know of alternatives or have RECENT tutorials on using it with Laravel?
Thanks 🙏 submitted by /u/LikeAnElephant
[link] [comments]
Has Turbolinks pretty much become exclusive to Ruby on Rails? Anyone know of alternatives or have RECENT tutorials on using it with Laravel?
Thanks 🙏 submitted by /u/LikeAnElephant
[link] [comments]
Supercharge your Laravel app with custom data types in PostgreSQL
submitted by /u/the_kautilya
[link] [comments]
[link] [comments]
My "Model Required Fields" package
With Model Required Fields package, you can get the required model fields, excluding primary keys, nullable fields, and fields with defaults.
I first needed this information while working on a large project with no tests or factories and many migrations. It was distracting to manually look for each required field.
I created a simple trait to fetch required fields. It was easy in Laravel 11 and 10. Then I realized that most programmers who face this problem are usually using older versions, so I added support for Laravel 9, 8, 7, and 6, and extracted the logic into a package.
I tested the code for each supported Laravel version and each SQL database: SQLite, MySQL, MariaDB, PostgreSQL, and Microsoft SQL Server. I needed to add support for each SQL database because I used the DB facade with raw SQL queries, and there were slight differences each time.
The package is fully tested with PHPUnit and GitHub Actions for every Laravel version and for each database.
The usage and examples are in the readme file.
I hope you like this package, and I welcome any contributions or comments.
package link:
https://github.com/watheqAlshowaiter/model-required-fields. submitted by /u/watheq_show
[link] [comments]
I first needed this information while working on a large project with no tests or factories and many migrations. It was distracting to manually look for each required field.
I created a simple trait to fetch required fields. It was easy in Laravel 11 and 10. Then I realized that most programmers who face this problem are usually using older versions, so I added support for Laravel 9, 8, 7, and 6, and extracted the logic into a package.
I tested the code for each supported Laravel version and each SQL database: SQLite, MySQL, MariaDB, PostgreSQL, and Microsoft SQL Server. I needed to add support for each SQL database because I used the DB facade with raw SQL queries, and there were slight differences each time.
The package is fully tested with PHPUnit and GitHub Actions for every Laravel version and for each database.
The usage and examples are in the readme file.
I hope you like this package, and I welcome any contributions or comments.
package link:
https://github.com/watheqAlshowaiter/model-required-fields. submitted by /u/watheq_show
[link] [comments]
09 July, 2024
Quick tip about model serialization in event constructor
I had an issue with relations being resolved during unserialization, but because there is a polymorphic relation sometimes it can try to resolve a nested relation that does not exist anymore. Use the #[WithoutRelations] attribute to fix it. submitted by /u/imwearingyourpants
[link] [comments]
[link] [comments]
08 July, 2024
How to find ceritain value in multiple section and return other value
How should I write this formula
Find the Square section where Value A at (Gary is in 8 in this case), and get the name " Ocho" from list underneath
then find where is Value B, Put Ocho at highlight place in value B section
Then list the rest clockwise
Sample Image:
I tried to put value clockwise by using
=INDEX(D22:D29,,XMATCH(D22:D29,MOD(SEQUENCE(8,,E29-1),8)+1))
Find the Square section where Value A at (Gary is in 8 in this case), and get the name " Ocho" from list underneath
then find where is Value B, Put Ocho at highlight place in value B section
Then list the rest clockwise
Sample Image:
I tried to put value clockwise by using
=INDEX(D22:D29,,XMATCH(D22:D29,MOD(SEQUENCE(8,,E29-1),8)+1))
OpenCV - How to compute 3D points with SfM methods with known fundamental matrix
For a university project, we are working on implementing a basic SfM pipeline, using Middlebury's "temple" dataset. This means that, for each image, the projection matrix for that given image is known. I have done some reading and seen some examples on SfM reconstruction, where, usually, the camera rotation and translation are unknown and PnP algorithms are used to obtain them.
My question is, given we know the projection matrix for any given image, what would the processing pipeline look like? I envision something along the lines of:
* Compute SIFT keypoints and descriptors for each image.
* Pair "adjacent" images (in this case, images with sequential ids from the dataset)
* Find point matches for each pair using KNN or similar matching algorithm.
* Use cv2.triangulatePoints to find the corresponding 3D point for each of the 2d point matches using the known projection matrices.
I understand that, generally, the most difficult aspect of SfM is precisely the step we are skipping over of pose estimation. However, for now we are only aiming for a basic implementation, possibly implementing a "complete" algorithm that includes this step later.
Still, I am unsure as to whether there are any processing steps that would be necessary in order to obtain "good" results.
* Would something like undistortPoints be necessary for this estimation?
* What would be the most efficient way of building the point cloud (for example, building feature tracks and only include points that result from the triangulation of some number of images n)?
* Finally, where and how should we discard pair outliers? Most of the functions offered by OpenCV use RANSAC as part of the pose estimation process, and I don't know if there are functions that would allow us to use the algorithm in our case (if it would even be necessary).
So far, we have implemented a basic SIFT keypoint extractor.
Unsure where to continue from here.
My question is, given we know the projection matrix for any given image, what would the processing pipeline look like? I envision something along the lines of:
* Compute SIFT keypoints and descriptors for each image.
* Pair "adjacent" images (in this case, images with sequential ids from the dataset)
* Find point matches for each pair using KNN or similar matching algorithm.
* Use cv2.triangulatePoints to find the corresponding 3D point for each of the 2d point matches using the known projection matrices.
I understand that, generally, the most difficult aspect of SfM is precisely the step we are skipping over of pose estimation. However, for now we are only aiming for a basic implementation, possibly implementing a "complete" algorithm that includes this step later.
Still, I am unsure as to whether there are any processing steps that would be necessary in order to obtain "good" results.
* Would something like undistortPoints be necessary for this estimation?
* What would be the most efficient way of building the point cloud (for example, building feature tracks and only include points that result from the triangulation of some number of images n)?
* Finally, where and how should we discard pair outliers? Most of the functions offered by OpenCV use RANSAC as part of the pose estimation process, and I don't know if there are functions that would allow us to use the algorithm in our case (if it would even be necessary).
So far, we have implemented a basic SIFT keypoint extractor.
Unsure where to continue from here.
How to resolve a Cors error when trying to get an authentication token using authorisation code grant in Next.js
I have an app where im trying to send a generated pdf to get a signature. Pretty straightforward.
I got the authentication working in postman, but when I try it in code, I get this error:
Access to fetch at '
https://account-d.docusign.com/oauth/token' from origin '
http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I can retrieve the oauth code with this:
if (router.asPath !== router.route) {
setOAuthCode(new URLSearchParams(window.location.search).get("code"));
}
but in a seperate use effect, i try to submit this oAuth code, it falls appart:
useEffect(() => {
const getAuthToken = async () => {
const tokenUrl = "
https://account-d.docusign.com/oauth/token";
/> const encodedSecret = btoa(
`${process.env.NEXT_PUBLIC_DOCUSIGN_INTEGRATION_KEY}:${process.env.NEXT_PUBLIC_DOCUSIGN_CLIENT_SECRET}`
);
const headers = {
"Authorization": `Basic ${encodedSecret}`,
"Content-Type": "application/x-www-form-urlencoded",
};
const body = new URLSearchParams({
grant_type: "authorization_code",
code: oAuthCode,
});
const response = await fetch(tokenUrl, {
method: "POST",
headers: headers,
body: body,
});
if (!response.ok) {
throw new Error(
`Failed to get access token: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
setAuthToken(data.access_token);
};
getAuthToken();
}, [oAuthCode]);
Any kung fu would be greatfully accepted
I got the authentication working in postman, but when I try it in code, I get this error:
Access to fetch at '
https://account-d.docusign.com/oauth/token' from origin '
http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I can retrieve the oauth code with this:
if (router.asPath !== router.route) {
setOAuthCode(new URLSearchParams(window.location.search).get("code"));
}
but in a seperate use effect, i try to submit this oAuth code, it falls appart:
useEffect(() => {
const getAuthToken = async () => {
const tokenUrl = "
https://account-d.docusign.com/oauth/token";
/> const encodedSecret = btoa(
`${process.env.NEXT_PUBLIC_DOCUSIGN_INTEGRATION_KEY}:${process.env.NEXT_PUBLIC_DOCUSIGN_CLIENT_SECRET}`
);
const headers = {
"Authorization": `Basic ${encodedSecret}`,
"Content-Type": "application/x-www-form-urlencoded",
};
const body = new URLSearchParams({
grant_type: "authorization_code",
code: oAuthCode,
});
const response = await fetch(tokenUrl, {
method: "POST",
headers: headers,
body: body,
});
if (!response.ok) {
throw new Error(
`Failed to get access token: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
setAuthToken(data.access_token);
};
getAuthToken();
}, [oAuthCode]);
Any kung fu would be greatfully accepted
A laravel package to test/debug emails all at local machine
I am excited to announce that I have released new version of mailbase.
https://github.com/tkeer/mailbase
It lets you save your emails in database and go through each one by one.
If you use laravel mail feature I would love if you could check and let me know what do you think and how can I improve it. submitted by /u/tkeer
[link] [comments]
https://github.com/tkeer/mailbase
It lets you save your emails in database and go through each one by one.
If you use laravel mail feature I would love if you could check and let me know what do you think and how can I improve it. submitted by /u/tkeer
[link] [comments]
.Net 8 XUnit: Use an In-Memory DBConnection for testing as a replacement for the real MySqlConnection
I'm creating tests for my .Net 8 API, and as I want to test with fake self created data (instead of using the real MySql connection) I'm having problems figuring out how to implement that behavior, I mean, using -for example- an In-Memory database.
We use CQRS (Mediator pattern) for the database queries, and on each query handler we inject ICloudStackCoreConnectionFactory which includes (among others) a CreateConnection method that returns a DBConnection (in our case, a MySqlConnection):
ICloudStackCoreConnectionFactory:
public DbConnection CreateConnection(Region region)
{
return (DbConnection)new MySqlConnection(GetConnString(region));
}
I'd like to replace that MySqlConnection implementation by an in-memory connection so I can test with a reduced set of fake data, but I don't know how to do it.
We use a "Lab" to create all stuff needed for the tests, and the Lab includes a create method as follows:
public static Lab Create(ITestOutputHelper output)
{
var appFactory = Vdc.Libs.AspNet.Testing.Setup.Factory(
out var client,
out var authorize,
out var identity,
out var faker,
role: $"{VdcSecurity.Role.Management},{VdcSecurity.Role.ManagementAdmin}",
output: output,
setup: services =>
{
}
);
return new Lab(identity, appFactory, client, authorize, faker);
}
I know I could use Mock library to mock the ICloudStackCoreConnectionFactory interface, but as I debug, when the test starts the real "Program.cs" is launched, so is clear we are using the real hosted services and so I don't know how to replace only that interface with the mocked one.
Then I also don't know how to return a DBConnection In-Memory database with data in the "CreateConnection" method.
Any help?
Edit 1: The actual implementation of ICloudStackCoreConnectionFactory
//
// Summary:
// Allow create a connection with the CloudStack database for diferent regions
public sealed class MySqlCloudStackCoreConnectionFactory : ICloudStackCoreConnectionFactory
{
private sealed record QTaskInfo(Region Region, Task CountTask, Task DataTask);
private readonly CloudStackDBOptions _configuration;
private readonly ILogger _logger;
private static readonly ConcurrentDictionary _connections = new ConcurrentDictionary();
public MySqlCloudStackCoreConnectionFactory(IOptions options, ILogger logger)
{
_configuration = options.Value;
_logger = logger;
}
public DbConnection CreateConnection(Region region)
{
return new MySqlConnection(GetConnString(region));
}
public async Task QuerySearchAsync(IRegionRepository regionRepository, string fetchDataQuery, string? countDataQuery = null, Dictionary? columnModelModel = null, Paging? paging = null, ColumnName[]? order = null, string[]? excludedOrder = null, Func? transform = null, object? param = null, Func? filter = null, bool skipDbPaging = false, CancellationToken ct = default(CancellationToken)) where TOut : class
{
string[] excludedOrder2 = excludedOrder;
int total = 0;
List response = new List();
List connections = new List();
StringBuilder stringBuilder = new StringBuilder(fetchDataQuery);
if (order != null && excludedOrder2 != null && excludedOrder2.Length != 0)
{
order = order.Where((ColumnName o) => !excludedOrder2.Contains(o.Name)).ToArray();
}
if (order != null && order.Length != 0)
{
stringBuilder.Append(" ORDER BY");
ColumnName[] array = order;
foreach (ColumnName columnName in array)
{
string value = ((columnModelModel != null) ? columnModelModel[columnName.Name] : columnName.Name);
stringBuilder.Append(' ').Append(value).Append(columnName.Asc ? " ASC," : " DESC,");
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
}
if (paging != null && !skipDbPaging)
{
stringBuilder.Append(" LIMIT ").Append((paging.Page + 1) * paging.PageSize).Append(';');
}
fetchDataQuery = stringBuilder.ToString();
QTaskInfo[] array2 = ParallelizeTask(fetchDataQuery, countDataQuery, param, connections, await GetOnlineRegion(regionRepository, filter, ct));
Task[] array3 = new Task[2 * array2.Length];
for (int j = 0; j < array3.Length; j += 2)
{
int num = j / 2;
array3[j] = array2[num].CountTask;
array3[j + 1] = array2[num].DataTask;
}
Task.WaitAll(array3, ct);
ValueTask[] array4 = CloseConnection(connections);
for (int k = 0; k < array2.Length; k++)
{
var (region2, task3, task4) = array2[k];
try
{
IEnumerable result2 = task4.Result;
int result3 = task3.Result;
total += result3;
foreach (TDbItem item in result2)
{
TOut val = ((transform != null) ? transform(region2, item) : null) ?? (item as TOut);
if (val != null)
{
response.Add(val);
}
}
}
catch (Exception exception)
{
regionRepository.SetStatus(region2, online: false);
_logger.LogError(exception, "Error request region: {Region}", region2);
}
}
IQueryable result = response.AsQueryable().ApplySearch(paging, order);
_logger.LogInformation("Dispose all connection created");
ValueTask[] array5 = array4;
for (int l = 0; l < array5.Length; l++)
{
ValueTask valueTask = array5[l];
await valueTask;
}
TOut[] array6 = result.ToArray();
return ((countDataQuery == null) ? array6.Length : total, array6);
}
public async Task ExecuteAsync(IRegionRepository regionRepository, string sql, object? @params = null, Func? filter = null, CancellationToken ct = default(CancellationToken))
{
string sql2 = sql;
object params2 = @params;
Region[] array = await GetOnlineRegion(regionRepository, filter, ct);
List connections = new List();
Region[] array2 = new Region[array.Length];
Task[] array3 = new Task[array.Length];
for (int i = 0; i < array3.Length; i++)
{
Region region = array[i];
_logger.LogInformation("Creating connection for: {Region}", region);
DbConnection connection = CreateConnection(region);
Task task = Task.Run(async delegate
{
try
{
_logger.LogDebug("Creating connection for: {Region}", region);
return await connection.ExecuteAsync(sql2, params2);
}
catch (Exception exception2)
{
_logger.LogWarning(exception2, "Error query {Region}", region);
return 0;
}
});
array3[i] = task;
array2[i] = region;
}
Task[] tasks = array3;
Task.WaitAll(tasks, ct);
ValueTask[] array4 = CloseConnection(connections);
int total = 0;
for (int j = 0; j < array3.Length; j++)
{
Task task2 = array3[j];
Region region2 = array2[j];
try
{
int result = task2.Result;
total += result;
}
catch (Exception exception)
{
regionRepository.SetStatus(region2, online: false);
_logger.LogError(exception, "Error request region: {Region}", region2);
}
}
_logger.LogInformation("Dispose all connection created");
ValueTask[] array5 = array4;
for (int k = 0; k < array5.Length; k++)
{
ValueTask valueTask = array5[k];
await valueTask;
}
return total;
}
private static ValueTask[] CloseConnection(List connections)
{
return connections.Select((DbConnection s) => s.DisposeAsync()).ToArray();
}
private string GetConnString(Region region)
{
return region switch
{
Region.Europe => _configuration.Europe,
Region.Asia => _configuration.Asia,
Region.NA => _configuration.NA,
Region.Lab => _configuration.Lab,
_ => throw new NotSupportedException("Region is not supported"),
};
}
private static async Task GetOnlineRegion(IRegionRepository regionRepository, Func? filter = null, CancellationToken ct = default(CancellationToken))
{
Func filter2 = filter;
return (from p in await regionRepository.GetOnlineAsync(ct)
where p != Region.Lab
where filter2?.Invoke(p) ?? true
select p).ToArray();
}
private QTaskInfo[] ParallelizeTask(string fetchDataQuery, string? countDataQuery, object? param, List connections, Region[] onlineRegions)
{
string fetchDataQuery2 = fetchDataQuery;
object param2 = param;
string countDataQuery2 = countDataQuery;
QTaskInfo[] array = new QTaskInfo[onlineRegions.Length];
for (int i = 0; i < array.Length; i++)
{
Region region = onlineRegions[i];
_logger.LogInformation("Creating connection for: {Region}", region);
DbConnection dataConnection = CreateConnection(region);
if (!_connections.GetOrAdd(region, value: false))
{
lock (_connections)
{
if (!_connections.GetValueOrDefault(region))
{
dataConnection.Open();
_connections[region] = true;
}
}
}
Task dataTask = Task.Run(async delegate
{
try
{
_logger.LogDebug("Run Query {Query} with {Args}", fetchDataQuery2, param2);
return await dataConnection.QueryAsync(fetchDataQuery2, param2);
}
catch (Exception exception2)
{
_logger.LogWarning(exception2, "Error query {Region}", region);
return Array.Empty();
}
});
Task countTask;
if (!string.IsNullOrEmpty(countDataQuery2))
{
DbConnection countConnection = CreateConnection(region);
countTask = Task.Run(async delegate
{
try
{
_logger.LogDebug("Run Query {Query} with {Args}", countDataQuery2, param2);
return await countConnection.ExecuteScalarAsync(countDataQuery2, param2);
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Error query {Region}", region);
return 0;
}
});
connections.Add(countConnection);
}
else
{
countTask = Task.FromResult(0);
}
connections.Add(dataConnection);
array[i] = new QTaskInfo(region, countTask, dataTask);
}
return array;
}
}
Edit 2: This is our comple "Lab" class we use to initialize all elements needed for the tests (maybe it helps):
Lab.cs:
public sealed class Lab
{
private readonly Faker _faker;
private readonly IdentityInfo _identity;
private readonly WebApplicationFactory _appFactory;
private readonly IApiClient _apiClient;
private readonly AuthorizeOptions _authorize;
private readonly Account[] _data;
private Lab(IdentityInfo identity, WebApplicationFactory appFactory, IApiClient apiClient, AuthorizeOptions authorize, Faker faker)
{
_faker = faker;
_identity = identity;
_appFactory = appFactory;
_apiClient = apiClient;
_authorize = authorize;
_data = [
CreateAccount("Account1", AccountTypes.Managed),
CreateAccount("Account2", AccountTypes.Managed),
CreateAccount("Account3", AccountTypes.Unmanaged),
CreateAccount("Account4", AccountTypes.Internal),
CreateAccount("Account5", AccountTypes.Hybrid),
CreateAccount("Account6", AccountTypes.Hybrid),
CreateAccount("Account7", AccountTypes.Hybrid),
CreateAccount("Account8", AccountTypes.Hybrid)
];
}
public Faker Faker => _faker;
public Account[] Jobs => _data;
public IdentityInfo Identity => _identity;
public IApiClient ApiClient => _apiClient;
public AuthorizeOptions Authorize => _authorize;
public WebApplicationFactory AppFactory => _appFactory;
public async Task InitAsync(IServiceProvider provider, bool useEvents = false)
{
var unitOfWork = provider.GetRequiredService();
//PopulateStatus(provider);
PopulateAccounts(provider, _data);
await unitOfWork.SaveChangesAsync();
EventSend? events = null;
if (useEvents)
Events.Capture(provider, events = new EventSend());
return events;
// ==============================================================================================================
static void PopulateAccounts(IServiceProvider provider, Account[] dataSample)
{
var accountRepository = provider.GetRequiredService();
IEnumerable data = dataSample;
accountRepository.AddRange(data.ToArray());
}
}
///
/// Create a lab with the requirement of this project
///
///
///
///
///
public static Lab Create(ITestOutputHelper output)
{
var appFactory = Vdc.Libs.AspNet.Testing.Setup.Factory(
out var client,
out var authorize,
out var identity,
out var faker,
role: $"{VdcSecurity.Role.Management},{VdcSecurity.Role.ManagementAdmin}",
output: output,
setup: services =>
{
services.AddScoped();
}
);
return new Lab(identity, appFactory, client, authorize, faker);
}
#region Private Methods
private Account CreateAccount(string accountName, AccountTypes typeId)
{
Account account;
var serializer = AppFactory.Services.GetRequiredService();
account = new Account
{
Id = Guid.NewGuid(),
Name = accountName,
CloudStackAccounts = new List(),
TypeId = typeId,
Order = 0
//Deleted = _faker.Date.Past(),
//SLID = _faker.Random.String2(6),
};
return account;
}
#endregion
}
We use CQRS (Mediator pattern) for the database queries, and on each query handler we inject ICloudStackCoreConnectionFactory which includes (among others) a CreateConnection method that returns a DBConnection (in our case, a MySqlConnection):
ICloudStackCoreConnectionFactory:
public DbConnection CreateConnection(Region region)
{
return (DbConnection)new MySqlConnection(GetConnString(region));
}
I'd like to replace that MySqlConnection implementation by an in-memory connection so I can test with a reduced set of fake data, but I don't know how to do it.
We use a "Lab" to create all stuff needed for the tests, and the Lab includes a create method as follows:
public static Lab Create(ITestOutputHelper output)
{
var appFactory = Vdc.Libs.AspNet.Testing.Setup.Factory(
out var client,
out var authorize,
out var identity,
out var faker,
role: $"{VdcSecurity.Role.Management},{VdcSecurity.Role.ManagementAdmin}",
output: output,
setup: services =>
{
}
);
return new Lab(identity, appFactory, client, authorize, faker);
}
I know I could use Mock library to mock the ICloudStackCoreConnectionFactory interface, but as I debug, when the test starts the real "Program.cs" is launched, so is clear we are using the real hosted services and so I don't know how to replace only that interface with the mocked one.
Then I also don't know how to return a DBConnection In-Memory database with data in the "CreateConnection" method.
Any help?
Edit 1: The actual implementation of ICloudStackCoreConnectionFactory
//
// Summary:
// Allow create a connection with the CloudStack database for diferent regions
public sealed class MySqlCloudStackCoreConnectionFactory : ICloudStackCoreConnectionFactory
{
private sealed record QTaskInfo(Region Region, Task CountTask, Task DataTask);
private readonly CloudStackDBOptions _configuration;
private readonly ILogger _logger;
private static readonly ConcurrentDictionary _connections = new ConcurrentDictionary();
public MySqlCloudStackCoreConnectionFactory(IOptions options, ILogger logger)
{
_configuration = options.Value;
_logger = logger;
}
public DbConnection CreateConnection(Region region)
{
return new MySqlConnection(GetConnString(region));
}
public async Task QuerySearchAsync(IRegionRepository regionRepository, string fetchDataQuery, string? countDataQuery = null, Dictionary? columnModelModel = null, Paging? paging = null, ColumnName[]? order = null, string[]? excludedOrder = null, Func? transform = null, object? param = null, Func? filter = null, bool skipDbPaging = false, CancellationToken ct = default(CancellationToken)) where TOut : class
{
string[] excludedOrder2 = excludedOrder;
int total = 0;
List response = new List();
List connections = new List();
StringBuilder stringBuilder = new StringBuilder(fetchDataQuery);
if (order != null && excludedOrder2 != null && excludedOrder2.Length != 0)
{
order = order.Where((ColumnName o) => !excludedOrder2.Contains(o.Name)).ToArray();
}
if (order != null && order.Length != 0)
{
stringBuilder.Append(" ORDER BY");
ColumnName[] array = order;
foreach (ColumnName columnName in array)
{
string value = ((columnModelModel != null) ? columnModelModel[columnName.Name] : columnName.Name);
stringBuilder.Append(' ').Append(value).Append(columnName.Asc ? " ASC," : " DESC,");
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
}
if (paging != null && !skipDbPaging)
{
stringBuilder.Append(" LIMIT ").Append((paging.Page + 1) * paging.PageSize).Append(';');
}
fetchDataQuery = stringBuilder.ToString();
QTaskInfo[] array2 = ParallelizeTask(fetchDataQuery, countDataQuery, param, connections, await GetOnlineRegion(regionRepository, filter, ct));
Task[] array3 = new Task[2 * array2.Length];
for (int j = 0; j < array3.Length; j += 2)
{
int num = j / 2;
array3[j] = array2[num].CountTask;
array3[j + 1] = array2[num].DataTask;
}
Task.WaitAll(array3, ct);
ValueTask[] array4 = CloseConnection(connections);
for (int k = 0; k < array2.Length; k++)
{
var (region2, task3, task4) = array2[k];
try
{
IEnumerable result2 = task4.Result;
int result3 = task3.Result;
total += result3;
foreach (TDbItem item in result2)
{
TOut val = ((transform != null) ? transform(region2, item) : null) ?? (item as TOut);
if (val != null)
{
response.Add(val);
}
}
}
catch (Exception exception)
{
regionRepository.SetStatus(region2, online: false);
_logger.LogError(exception, "Error request region: {Region}", region2);
}
}
IQueryable result = response.AsQueryable().ApplySearch(paging, order);
_logger.LogInformation("Dispose all connection created");
ValueTask[] array5 = array4;
for (int l = 0; l < array5.Length; l++)
{
ValueTask valueTask = array5[l];
await valueTask;
}
TOut[] array6 = result.ToArray();
return ((countDataQuery == null) ? array6.Length : total, array6);
}
public async Task ExecuteAsync(IRegionRepository regionRepository, string sql, object? @params = null, Func? filter = null, CancellationToken ct = default(CancellationToken))
{
string sql2 = sql;
object params2 = @params;
Region[] array = await GetOnlineRegion(regionRepository, filter, ct);
List connections = new List();
Region[] array2 = new Region[array.Length];
Task[] array3 = new Task[array.Length];
for (int i = 0; i < array3.Length; i++)
{
Region region = array[i];
_logger.LogInformation("Creating connection for: {Region}", region);
DbConnection connection = CreateConnection(region);
Task task = Task.Run(async delegate
{
try
{
_logger.LogDebug("Creating connection for: {Region}", region);
return await connection.ExecuteAsync(sql2, params2);
}
catch (Exception exception2)
{
_logger.LogWarning(exception2, "Error query {Region}", region);
return 0;
}
});
array3[i] = task;
array2[i] = region;
}
Task[] tasks = array3;
Task.WaitAll(tasks, ct);
ValueTask[] array4 = CloseConnection(connections);
int total = 0;
for (int j = 0; j < array3.Length; j++)
{
Task task2 = array3[j];
Region region2 = array2[j];
try
{
int result = task2.Result;
total += result;
}
catch (Exception exception)
{
regionRepository.SetStatus(region2, online: false);
_logger.LogError(exception, "Error request region: {Region}", region2);
}
}
_logger.LogInformation("Dispose all connection created");
ValueTask[] array5 = array4;
for (int k = 0; k < array5.Length; k++)
{
ValueTask valueTask = array5[k];
await valueTask;
}
return total;
}
private static ValueTask[] CloseConnection(List connections)
{
return connections.Select((DbConnection s) => s.DisposeAsync()).ToArray();
}
private string GetConnString(Region region)
{
return region switch
{
Region.Europe => _configuration.Europe,
Region.Asia => _configuration.Asia,
Region.NA => _configuration.NA,
Region.Lab => _configuration.Lab,
_ => throw new NotSupportedException("Region is not supported"),
};
}
private static async Task GetOnlineRegion(IRegionRepository regionRepository, Func? filter = null, CancellationToken ct = default(CancellationToken))
{
Func filter2 = filter;
return (from p in await regionRepository.GetOnlineAsync(ct)
where p != Region.Lab
where filter2?.Invoke(p) ?? true
select p).ToArray();
}
private QTaskInfo[] ParallelizeTask(string fetchDataQuery, string? countDataQuery, object? param, List connections, Region[] onlineRegions)
{
string fetchDataQuery2 = fetchDataQuery;
object param2 = param;
string countDataQuery2 = countDataQuery;
QTaskInfo[] array = new QTaskInfo[onlineRegions.Length];
for (int i = 0; i < array.Length; i++)
{
Region region = onlineRegions[i];
_logger.LogInformation("Creating connection for: {Region}", region);
DbConnection dataConnection = CreateConnection(region);
if (!_connections.GetOrAdd(region, value: false))
{
lock (_connections)
{
if (!_connections.GetValueOrDefault(region))
{
dataConnection.Open();
_connections[region] = true;
}
}
}
Task dataTask = Task.Run(async delegate
{
try
{
_logger.LogDebug("Run Query {Query} with {Args}", fetchDataQuery2, param2);
return await dataConnection.QueryAsync(fetchDataQuery2, param2);
}
catch (Exception exception2)
{
_logger.LogWarning(exception2, "Error query {Region}", region);
return Array.Empty();
}
});
Task countTask;
if (!string.IsNullOrEmpty(countDataQuery2))
{
DbConnection countConnection = CreateConnection(region);
countTask = Task.Run(async delegate
{
try
{
_logger.LogDebug("Run Query {Query} with {Args}", countDataQuery2, param2);
return await countConnection.ExecuteScalarAsync(countDataQuery2, param2);
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Error query {Region}", region);
return 0;
}
});
connections.Add(countConnection);
}
else
{
countTask = Task.FromResult(0);
}
connections.Add(dataConnection);
array[i] = new QTaskInfo(region, countTask, dataTask);
}
return array;
}
}
Edit 2: This is our comple "Lab" class we use to initialize all elements needed for the tests (maybe it helps):
Lab.cs:
public sealed class Lab
{
private readonly Faker _faker;
private readonly IdentityInfo _identity;
private readonly WebApplicationFactory _appFactory;
private readonly IApiClient _apiClient;
private readonly AuthorizeOptions _authorize;
private readonly Account[] _data;
private Lab(IdentityInfo identity, WebApplicationFactory appFactory, IApiClient apiClient, AuthorizeOptions authorize, Faker faker)
{
_faker = faker;
_identity = identity;
_appFactory = appFactory;
_apiClient = apiClient;
_authorize = authorize;
_data = [
CreateAccount("Account1", AccountTypes.Managed),
CreateAccount("Account2", AccountTypes.Managed),
CreateAccount("Account3", AccountTypes.Unmanaged),
CreateAccount("Account4", AccountTypes.Internal),
CreateAccount("Account5", AccountTypes.Hybrid),
CreateAccount("Account6", AccountTypes.Hybrid),
CreateAccount("Account7", AccountTypes.Hybrid),
CreateAccount("Account8", AccountTypes.Hybrid)
];
}
public Faker Faker => _faker;
public Account[] Jobs => _data;
public IdentityInfo Identity => _identity;
public IApiClient ApiClient => _apiClient;
public AuthorizeOptions Authorize => _authorize;
public WebApplicationFactory AppFactory => _appFactory;
public async Task InitAsync(IServiceProvider provider, bool useEvents = false)
{
var unitOfWork = provider.GetRequiredService();
//PopulateStatus(provider);
PopulateAccounts(provider, _data);
await unitOfWork.SaveChangesAsync();
EventSend? events = null;
if (useEvents)
Events.Capture(provider, events = new EventSend());
return events;
// ==============================================================================================================
static void PopulateAccounts(IServiceProvider provider, Account[] dataSample)
{
var accountRepository = provider.GetRequiredService();
IEnumerable data = dataSample;
accountRepository.AddRange(data.ToArray());
}
}
///
/// Create a lab with the requirement of this project
///
///
///
///
///
public static Lab Create(ITestOutputHelper output)
{
var appFactory = Vdc.Libs.AspNet.Testing.Setup.Factory(
out var client,
out var authorize,
out var identity,
out var faker,
role: $"{VdcSecurity.Role.Management},{VdcSecurity.Role.ManagementAdmin}",
output: output,
setup: services =>
{
services.AddScoped();
}
);
return new Lab(identity, appFactory, client, authorize, faker);
}
#region Private Methods
private Account CreateAccount(string accountName, AccountTypes typeId)
{
Account account;
var serializer = AppFactory.Services.GetRequiredService();
account = new Account
{
Id = Guid.NewGuid(),
Name = accountName,
CloudStackAccounts = new List(),
TypeId = typeId,
Order = 0
//Deleted = _faker.Date.Past(),
//SLID = _faker.Random.String2(6),
};
return account;
}
#endregion
}
07 July, 2024
Pass multiple arguments to single command in custom position xargs
I want execute a command where I have the args as single string but they need to be in a custom position. E.g. in the following example I want the args to be positioned before any fixed args that I have written after the cp comamnd i.e. the path argument /somedir
I want:
echo -n 'file1 file2 file3' | xargs -d ' ' -I{} cp {} /somedir
to behave like:
cp file1 file2 file3 /somedir
but it doesn't...
It also looks like when including the -I{} option, the -d option makes xargs behave differently. It seems like it tries to pass each argument to a separate command call rather than all of them toa single one.
For example, this works:
echo -n 'file1 file2' | xargs -d' ' diff
But this fails
echo -n 'file1 file2' | xargs -d' ' -I{} diff {}
With error:
diff: missing operand after 'file1'
diff: Try 'diff --help' for more information.
diff: missing operand after 'file2'
diff: Try 'diff --help' for more information.
How can I get echo -n 'file1 file2 file3' | xargs -d ' ' -I{} cp {} /somedir to behave as intended
I want:
echo -n 'file1 file2 file3' | xargs -d ' ' -I{} cp {} /somedir
to behave like:
cp file1 file2 file3 /somedir
but it doesn't...
It also looks like when including the -I{} option, the -d option makes xargs behave differently. It seems like it tries to pass each argument to a separate command call rather than all of them toa single one.
For example, this works:
echo -n 'file1 file2' | xargs -d' ' diff
But this fails
echo -n 'file1 file2' | xargs -d' ' -I{} diff {}
With error:
diff: missing operand after 'file1'
diff: Try 'diff --help' for more information.
diff: missing operand after 'file2'
diff: Try 'diff --help' for more information.
How can I get echo -n 'file1 file2 file3' | xargs -d ' ' -I{} cp {} /somedir to behave as intended
Problemas com a biblioteca customtkinter
enter image description here
Estou desenvolvendo um projeto para meu TCC só que a biblioteca TKinter vem apresentando alguns bugs, muitas vezes tenho que apertar o botão de login várias vezes para realmente realizar o login, existe alguma alternativa para corrigir esse possível bug.
#btn login
self.btn_login = ctk.CTkButton(self.frame_login, width=300, text='Login'.upper(), font=('Roboto bold', 16, 'bold'), corner_radius=15, command=self.verifica_login)
self.btn_login.grid(row=4, column=0, padx=10, pady=10)
Estou desenvolvendo um projeto para meu TCC só que a biblioteca TKinter vem apresentando alguns bugs, muitas vezes tenho que apertar o botão de login várias vezes para realmente realizar o login, existe alguma alternativa para corrigir esse possível bug.
#btn login
self.btn_login = ctk.CTkButton(self.frame_login, width=300, text='Login'.upper(), font=('Roboto bold', 16, 'bold'), corner_radius=15, command=self.verifica_login)
self.btn_login.grid(row=4, column=0, padx=10, pady=10)
Image not loading in HTML page when trying to change using GetElementByID method
I am attempting to write an simple function in an HTML page which displays the image and there are few buttons which change the image I have used the "document.getElementById('myImage').src= " command to change it but there is no image shows after I click the image. The same image is loading properly using the tag. The same button works if I use a link direct taken from google. Below I have pasted the code. Any suggestions are appreciated.
This page shows changing emotions using various buttons
Envy
Angry
Sad
Embarassed
Happy
Anxiety
Tried links from Google it works but local images does not work in the on click function Thank you!
This page shows changing emotions using various buttons
Envy
Angry
Sad
Embarassed
Happy
Anxiety
Tried links from Google it works but local images does not work in the on click function Thank you!
Weekly /r/Laravel Help Thread
Ask your Laravel help questions here. To improve your chances of getting an answer from the community, here are some tips:
* What steps have you taken so far?
* What have you tried from the documentation?
* Did you provide any error messages you are getting?
* Are you able to provide instructions to replicate the issue?
* Did you provide a code example?
* Please don't post a screenshot of your code. Use the code block in the Reddit text editor and ensure it's formatted correctly.
For more immediate support, you can ask in the official Laravel Discord.
Thanks and welcome to the /r/Laravel community! submitted by /u/AutoModerator
[link] [comments]
* What steps have you taken so far?
* What have you tried from the documentation?
* Did you provide any error messages you are getting?
* Are you able to provide instructions to replicate the issue?
* Did you provide a code example?
* Please don't post a screenshot of your code. Use the code block in the Reddit text editor and ensure it's formatted correctly.
For more immediate support, you can ask in the official Laravel Discord.
Thanks and welcome to the /r/Laravel community! submitted by /u/AutoModerator
[link] [comments]
Laravel Livewire Filemanager
Hello there! I have created my first open source package! It's a simple and easy to use filemanager for your laravel apps!
It's still in development but any feedbacks and ideas are welcome !
https://github.com/livewire-filemanager/filemanager submitted by /u/bee-interactive
[link] [comments]
It's still in development but any feedbacks and ideas are welcome !
https://github.com/livewire-filemanager/filemanager submitted by /u/bee-interactive
[link] [comments]
06 July, 2024
How to expand path to UNC including all server domain information?
I need to compare path strings, and can't work with any difference in the given information of an UNC path.
How to convert a path into the full UNC version, including server domain information, in Delphi?
thispath : String;
thispath := 'x:\testfolder_on_server';
thispath := ExpandUNCFIlename( thispath ) ; // '\\myserver\testfolder_on_server\'
But what I need is the UNC Path including all the domain information for my server path.
'\\myserver.local.commay\testfolder_on_server\'
How to convert a path into the full UNC version, including server domain information, in Delphi?
thispath : String;
thispath := 'x:\testfolder_on_server';
thispath := ExpandUNCFIlename( thispath ) ; // '\\myserver\testfolder_on_server\'
But what I need is the UNC Path including all the domain information for my server path.
'\\myserver.local.commay\testfolder_on_server\'
Temporary block when using Credential Manager to Sign in with Google
I'm testing the 'Sign in with Google' flow with Credential Manager by following the indications in the official docs. So far, the process works as intended: it shows a bottom sheet with the available accounts and it allows me to sign in to the selected account.
However, I observed that if I dismiss the bottom sheet 4 times in a row, the bottom sheet doesn't appear anymore and I get the following exception:
androidx.credentials.exceptions.NoCredentialException: During begin sign in, failure response from one tap: 16: [28436] Caller has been temporarily blocked due to too many canceled sign-in prompts.
That exception seems to come from the old 'One Tap' flow. As explained in the One Tap docs, "If a user cancels several prompts in a row, the One Tap client will not prompt the user for the next 24 hours".
Which leads to my question:
If a user who is trying to sign in into my app dismisses the credential prompt 4 times in a row (which I can easily see happening), what should I do? Telling them that they cannot use the app for 24 hours seems a bit excessive. Is there any alternative?
NOTE:
It's important to point out that the old GoogleSignInClient didn't have this limitation.
However, I observed that if I dismiss the bottom sheet 4 times in a row, the bottom sheet doesn't appear anymore and I get the following exception:
androidx.credentials.exceptions.NoCredentialException: During begin sign in, failure response from one tap: 16: [28436] Caller has been temporarily blocked due to too many canceled sign-in prompts.
That exception seems to come from the old 'One Tap' flow. As explained in the One Tap docs, "If a user cancels several prompts in a row, the One Tap client will not prompt the user for the next 24 hours".
Which leads to my question:
If a user who is trying to sign in into my app dismisses the credential prompt 4 times in a row (which I can easily see happening), what should I do? Telling them that they cannot use the app for 24 hours seems a bit excessive. Is there any alternative?
NOTE:
It's important to point out that the old GoogleSignInClient didn't have this limitation.
Laravel Breeze with PrimeVue v4
This is an follow up to my previous post about a "starter kit" I created with Laravel and PrimeVue components.
The project has been updated with the following new changes:
* Upgraded to Laravel 11
* Updated to use Laravel Breeze backend instead of Fortify (for the potential to abstract this project as a fork of laravel/breeze with custom stubs)
* Upgraded PrimeVue to v4 (overhauled theming and light/dark mode)
* Removed PrimeFlex and re-added Tailwind CSS for utility styling
Feedback is welcomed as a GitHub issue or PR, thanks!
https://github.com/connorabbas/primevue-auth-starter submitted by /u/DevDrJinx
[link] [comments]
The project has been updated with the following new changes:
* Upgraded to Laravel 11
* Updated to use Laravel Breeze backend instead of Fortify (for the potential to abstract this project as a fork of laravel/breeze with custom stubs)
* Upgraded PrimeVue to v4 (overhauled theming and light/dark mode)
* Removed PrimeFlex and re-added Tailwind CSS for utility styling
Feedback is welcomed as a GitHub issue or PR, thanks!
https://github.com/connorabbas/primevue-auth-starter submitted by /u/DevDrJinx
[link] [comments]
Is a back_insert_iterator valid for the lifetime of the container?
I think I know the answer to this, but I'd appreciate a sanity check.
Does iterator invalidation apply to std::back_insert_iterators?
#include
#include
#include
int main() {
auto v = std::vector{ 0, 1, 2 };
auto iter = std::back_inserter(v);
*iter++ = 3;
v.clear(); // invalidates iterators, but
*iter++ = 4; // back_insert_iterator is special?
assert(v.size() == 1 && v[0] == 4);
return 0;
}
This code works for me because the std::back_insert_iterator implementation from my vendor doesn't hold an iterator (or pointer or reference). It simply calls the container's push_back method.
But does the standard require that implementation? Could another vendor's back_insert_iterator hold and maintain a one-past-the-end iterator to use with a call to the container's insert method? It seems that would meet the requirements. This difference, of course, is that it would be vulnerable to invalidation.
---
I know cppreference.com is not authoritative, but it's more accessible than the standard.
[A vector's clear method] [i]nvalidates any ... iterators referring to contained elements. Any past-the-end iterators are also invalidated. [cppreference.com, emphasis added]
A std::back_insert_iterator could be the poster child of a past-the-end iterator.
Does iterator invalidation apply to std::back_insert_iterators?
#include
#include
#include
int main() {
auto v = std::vector{ 0, 1, 2 };
auto iter = std::back_inserter(v);
*iter++ = 3;
v.clear(); // invalidates iterators, but
*iter++ = 4; // back_insert_iterator is special?
assert(v.size() == 1 && v[0] == 4);
return 0;
}
This code works for me because the std::back_insert_iterator implementation from my vendor doesn't hold an iterator (or pointer or reference). It simply calls the container's push_back method.
But does the standard require that implementation? Could another vendor's back_insert_iterator hold and maintain a one-past-the-end iterator to use with a call to the container's insert method? It seems that would meet the requirements. This difference, of course, is that it would be vulnerable to invalidation.
---
I know cppreference.com is not authoritative, but it's more accessible than the standard.
[A vector's clear method] [i]nvalidates any ... iterators referring to contained elements. Any past-the-end iterators are also invalidated. [cppreference.com, emphasis added]
A std::back_insert_iterator could be the poster child of a past-the-end iterator.
My first laravel package
Hi! I just released the v1 of my first laravel package. This is a very simple one, and I'm happy to receive some feedbacks.
https://github.com/nadlambino/laravel-uploadable
Thanks! submitted by /u/Environmental-Put358
[link] [comments]
https://github.com/nadlambino/laravel-uploadable
Thanks! submitted by /u/Environmental-Put358
[link] [comments]
Preview canvas crashing because environmentObject not set properly
I have my preview canvas crashing because the environmentObject is not properly set.
The app itself builds and run properly.
Error message.
app crashed due to missing environment of type: TaskModel. To resolve this add .environmentObject(TaskModel(...)) to the appropriate preview.
My View with the #Preview macro looks like this.
struct CopyTaskListScreen: View {
@EnvironmentObject private var taskModel: TaskModel
var body: some View {
NavigationStack {
List(taskModel.tasks.sorted(by:
The app itself builds and run properly.
Error message.
app crashed due to missing environment of type: TaskModel. To resolve this add .environmentObject(TaskModel(...)) to the appropriate preview.
My View with the #Preview macro looks like this.
struct CopyTaskListScreen: View {
@EnvironmentObject private var taskModel: TaskModel
var body: some View {
NavigationStack {
List(taskModel.tasks.sorted(by:
I don't compile C# tutorial with Matlab engine
I write a tutorial C# API with Matlab using matlab.engine.
(I want to exchange data between C# and Matlab. However, I cannot use the library when compiling. How to hide error?
My code here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using MathWorks.MATLAB.Engine;
using MathWorks.MATLAB.Exceptions;
using MathWorks.MATLAB.Types;
using System;
namespace MathWorks.MATLAB.Engine.ConsoleExamples
{
public class Program
{
public static void Main(string[] args)
{
Console.Write("Starting MATLAB... ");
using (dynamic matlab = MATLABEngine.StartMATLAB())
{
Console.WriteLine("done.");
double[] A = matlab.linspace(-5.0, 5.0);
int[] sz = new int[] { 25, 4 };
double[,] B = matlab.reshape(A, sz);
}
// Call when you no longer need MATLAB Engine in your application.
MATLABEngine.TerminateEngineClient();
}
}
}
namespace UDP_virtual
{
internal static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
But I don't compile. I assume I don't add lib for C# file.
(I want to exchange data between C# and Matlab. However, I cannot use the library when compiling. How to hide error?
My code here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using MathWorks.MATLAB.Engine;
using MathWorks.MATLAB.Exceptions;
using MathWorks.MATLAB.Types;
using System;
namespace MathWorks.MATLAB.Engine.ConsoleExamples
{
public class Program
{
public static void Main(string[] args)
{
Console.Write("Starting MATLAB... ");
using (dynamic matlab = MATLABEngine.StartMATLAB())
{
Console.WriteLine("done.");
double[] A = matlab.linspace(-5.0, 5.0);
int[] sz = new int[] { 25, 4 };
double[,] B = matlab.reshape(A, sz);
}
// Call when you no longer need MATLAB Engine in your application.
MATLABEngine.TerminateEngineClient();
}
}
}
namespace UDP_virtual
{
internal static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
But I don't compile. I assume I don't add lib for C# file.
sorting algorithm in O(n) according a specific condition
Given an array A with n−1 numbers where n = 2k
for some integer k. One of the values appears exactly n/2
another appears exactly n/4, and so on. More formally, for all 1 ≤ k ≤ log n exists a value that appears exactly n/2^k times in the array. Describe an algorithm that sorts A with a run time complexity of Θ(n), and analyze its running time.
example: input: 5,1,2,1,2,2,2
output: 1,1,2,2,2,2,5
some important pointers:
1.the time comlexity should be Worst case
2.using a dictionary is not allowed
3.the solution should use a stack or other basic data structures
i tried using counting sort but it didnt work because the array doesnt contain values starting from 0 and up.
i also thought about using a hash map but the wanred time complexity would be expected and not worst case.
thanks for the help in advance
for some integer k. One of the values appears exactly n/2
another appears exactly n/4, and so on. More formally, for all 1 ≤ k ≤ log n exists a value that appears exactly n/2^k times in the array. Describe an algorithm that sorts A with a run time complexity of Θ(n), and analyze its running time.
example: input: 5,1,2,1,2,2,2
output: 1,1,2,2,2,2,5
some important pointers:
1.the time comlexity should be Worst case
2.using a dictionary is not allowed
3.the solution should use a stack or other basic data structures
i tried using counting sort but it didnt work because the array doesnt contain values starting from 0 and up.
i also thought about using a hash map but the wanred time complexity would be expected and not worst case.
thanks for the help in advance
04 July, 2024
What rector rules do you use?
I have been playing around with Rector to ensure a more consistent codebase and there are a lot of rules to choose from. Additionally there's even a Laravel Rector package with more rules to choose from on top of that.
I am using a few, such as the early return rules and moving the property to the constructor as I think they're niceties but I'm interested in what rules the wider community uses.
All the rules seem like such good ideas but I'm not sure if it is wise to use them all, even if the application is pretty well tested. submitted by /u/TertiaryOrbit
[link] [comments]
I am using a few, such as the early return rules and moving the property to the constructor as I think they're niceties but I'm interested in what rules the wider community uses.
All the rules seem like such good ideas but I'm not sure if it is wise to use them all, even if the application is pretty well tested. submitted by /u/TertiaryOrbit
[link] [comments]
Scramble 0.11.0 – Laravel API documentation generator update: Laravel Data support, ability to enforce schema types, inference improvements
submitted by /u/RomaLytvynenko
[link] [comments]
[link] [comments]
03 July, 2024
how can i find message window in Quartus
There are no messages window below the code blocks
I'm using Quartus eda tool for fpga jobs with verilog HDL.
For compiling, i need message window to know errors in my code blocks.
But i can't find message window that indicate errors below the code blocks.
I wanted to extend code blocks so i dragged with my mouse and reduced messages window.
I compiled my code blocks but no messages window appeared.
So, I tried to solve problems in two ways but it didn't worked.
First, I tried rebooting the program.
Next, i clicked the window bar but message window didn't appear.
Thanks for reading. Hopes for good answers.
I'm using Quartus eda tool for fpga jobs with verilog HDL.
For compiling, i need message window to know errors in my code blocks.
But i can't find message window that indicate errors below the code blocks.
I wanted to extend code blocks so i dragged with my mouse and reduced messages window.
I compiled my code blocks but no messages window appeared.
So, I tried to solve problems in two ways but it didn't worked.
First, I tried rebooting the program.
Next, i clicked the window bar but message window didn't appear.
Thanks for reading. Hopes for good answers.
is there a way to print a bank check from a template where the user only puts the amount and the name?
I've been trying on excel to create a template for printing a bank check i've set the dimensions and everything but always has the print issues as it's not perfectly aligned so i've thought in some other way like coding an entire program in python (gui) that only needs the information (amount, location, date, name), it did create a pdf file but when i print it, it doesn't align well, like for example the amount isn't exactly put in the box of the check, same goes for the amount in letters.
Guys i really need help in this, i'm so lost in this i've tried everything
this is the code of the program i did,
import tkinter as tk
from fpdf import FPDF
import num2words
def generate_cheque():
amount = amount_entry.get().replace(" ", "")
amount_parts = amount.split(".")
amount_in_letters = num2words.num2words(int(amount_parts[0]), lang='fr').replace("virgule", "comma").replace("zero", "")
amount_in_letters += " dinars algeriens"
if int(amount_parts[1]) > 0:
amount_in_letters += " et " + num2words.num2words(int(amount_parts[1]), lang='fr').replace("virgule", "comma").replace("zero", "") + " centimes"
location = location_entry.get()
date = date_entry.get()
company_name = company_name_entry.get()
# Convert dimensions from inches to points
width_in_inches = 8.5
height_in_inches = 3.5
width_in_points = width_in_inches * 72
height_in_points = height_in_inches * 72
pdf = FPDF(unit="pt", format=(width_in_points, height_in_points))
pdf.add_page()
pdf.set_font("Arial", size=12)
# Add date
pdf.set_xy(480, 150)
pdf.cell(0, 10, txt=date, align="R")
# Add amount in numbers
pdf.set_xy(450, 50)
pdf.cell(0, 10, txt=amount, align="R")
# add location
pdf.set_xy(400,150)
pdf.cell(0,10, txt=location, align="L")
# Add amount in letters
pdf.set_xy(110,70)
pdf.multi_cell(0, 10, txt=amount_in_letters, align="L")
# Add company name
pdf.set_xy(50, 120)
pdf.cell(0, 10, txt=company_name, align="L")
# Save the PDF
pdf.output("cheque.pdf", "F")
result_label.config(text="Cheque generated successfully!")
root = tk.Tk()
root.title("Cheque Generator")
amount_label = tk.Label(root, text="Amount (000 000 000.00):")
amount_label.pack()
amount_entry = tk.Entry(root)
amount_entry.pack()
location_label = tk.Label(root, text="Location:")
location_label.pack()
location_entry = tk.Entry(root)
location_entry.pack()
date_label = tk.Label(root, text="Date (DD.MM.YYYY):")
date_label.pack()
date_entry = tk.Entry(root)
date_entry.pack()
company_name_label = tk.Label(root, text="Company Name:")
company_name_label.pack()
company_name_entry = tk.Entry(root)
company_name_entry.pack()
generate_button = tk.Button(root, text="Generate Cheque", command=generate_cheque)
generate_button.pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
is there a way to like creates the perfectly aligned pdf check file?
Guys i really need help in this, i'm so lost in this i've tried everything
this is the code of the program i did,
import tkinter as tk
from fpdf import FPDF
import num2words
def generate_cheque():
amount = amount_entry.get().replace(" ", "")
amount_parts = amount.split(".")
amount_in_letters = num2words.num2words(int(amount_parts[0]), lang='fr').replace("virgule", "comma").replace("zero", "")
amount_in_letters += " dinars algeriens"
if int(amount_parts[1]) > 0:
amount_in_letters += " et " + num2words.num2words(int(amount_parts[1]), lang='fr').replace("virgule", "comma").replace("zero", "") + " centimes"
location = location_entry.get()
date = date_entry.get()
company_name = company_name_entry.get()
# Convert dimensions from inches to points
width_in_inches = 8.5
height_in_inches = 3.5
width_in_points = width_in_inches * 72
height_in_points = height_in_inches * 72
pdf = FPDF(unit="pt", format=(width_in_points, height_in_points))
pdf.add_page()
pdf.set_font("Arial", size=12)
# Add date
pdf.set_xy(480, 150)
pdf.cell(0, 10, txt=date, align="R")
# Add amount in numbers
pdf.set_xy(450, 50)
pdf.cell(0, 10, txt=amount, align="R")
# add location
pdf.set_xy(400,150)
pdf.cell(0,10, txt=location, align="L")
# Add amount in letters
pdf.set_xy(110,70)
pdf.multi_cell(0, 10, txt=amount_in_letters, align="L")
# Add company name
pdf.set_xy(50, 120)
pdf.cell(0, 10, txt=company_name, align="L")
# Save the PDF
pdf.output("cheque.pdf", "F")
result_label.config(text="Cheque generated successfully!")
root = tk.Tk()
root.title("Cheque Generator")
amount_label = tk.Label(root, text="Amount (000 000 000.00):")
amount_label.pack()
amount_entry = tk.Entry(root)
amount_entry.pack()
location_label = tk.Label(root, text="Location:")
location_label.pack()
location_entry = tk.Entry(root)
location_entry.pack()
date_label = tk.Label(root, text="Date (DD.MM.YYYY):")
date_label.pack()
date_entry = tk.Entry(root)
date_entry.pack()
company_name_label = tk.Label(root, text="Company Name:")
company_name_label.pack()
company_name_entry = tk.Entry(root)
company_name_entry.pack()
generate_button = tk.Button(root, text="Generate Cheque", command=generate_cheque)
generate_button.pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
is there a way to like creates the perfectly aligned pdf check file?
Salt-Stack: Looking for a neet way to enforce a state only if a minon has seLinux installed
I have code that installs a custom seLinux module. In my fleet of minions there's Fedora based systems (with seLinux installed) and Debian based ones (without seLinux). On the latter the module/installing state should not be used and I am thus looking for a way of retrieving a neat answer to the question "is seLinux installed on this system?" (NOT "is seLinux enforcing on this system?") to use in a corresponding jinja2 if clause.
Attempts that have me despairing are:
* there appears to be no state in salt querying whether a given binary is on the $PATH - checking for sestatus is what I was after here.
* salt.states.selinux is not available on systems devoid of seLinux, so it's functionality does not help.
* I could not find any salt functionality to query for the local availability of something like salt.states.selinux (see above) either.
Any hint on how to go about this is appreciated.
Attempts that have me despairing are:
* there appears to be no state in salt querying whether a given binary is on the $PATH - checking for sestatus is what I was after here.
* salt.states.selinux is not available on systems devoid of seLinux, so it's functionality does not help.
* I could not find any salt functionality to query for the local availability of something like salt.states.selinux (see above) either.
Any hint on how to go about this is appreciated.
Laravel v11.14.0 Released: Improvements server log and support in Stringable class for Markdown extensions - msamgan.com
Discover Laravel v11.14.0 with enhanced server log improvements and expanded Markdown extension support in the Stringable class. Explore the latest updates for your Laravel projects.
https://msamgan.com/laravel-v11140-released-improvements-server-log-and-support-in-stringable-class-for-markdown-extensions submitted by /u/samgan-khan
[link] [comments]
https://msamgan.com/laravel-v11140-released-improvements-server-log-and-support-in-stringable-class-for-markdown-extensions submitted by /u/samgan-khan
[link] [comments]
allure reports not running, although allure is installed - allure command not found
I am using Nightwatch js, and have allure installed, and have been using reports successfully. However, something has changed, and now I get the following error:
$ allure generate ./allure-results --clean && allure open
bash: allure: command not found
I have allure-report folder and allure-results folder. Results folder holds up to date records, but nothing is being written to report folder.
Package.json looks correct - contains references to allure:
{
"name": "automation-poc",
"version": "2.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "./node_modules/.bin/nightwatch --retries 1",
"cleanConfigFiles": "del 'config/*.conf.js'",
"cleanReports": "del 'reports/*'"
},
"author": "Alex",
"license": "ISC",
"dependencies": {
"allure-commandline": "^2.29.0",
"chromedriver": "^94.0.0",
"csvtojson": "^2.0.10",
"del": "^4.1.1",
"del-cli": "^5.0.0",
"nightwatch": "^2.2.3",
"nightwatch-allure": "^1.2.0",
"selenium-server": "^3.141.59",
"uuid": "^10.0.0",
"yargs": "^15.3.1"
}
}
I've run various commands:
npm install allure-commandline
npm install nightwatch-allure
allure generate ./allure-results --clean && allure open
allure --version
npm install -g allure-commandline
npm install -g nightwatch-allure
I've made sure there's an entry in System Variables for the location of \node_modules\allure-commandline\bin
I've tried deleting the node_modules folder and running npm install again
$ allure generate ./allure-results --clean && allure open
bash: allure: command not found
I have allure-report folder and allure-results folder. Results folder holds up to date records, but nothing is being written to report folder.
Package.json looks correct - contains references to allure:
{
"name": "automation-poc",
"version": "2.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "./node_modules/.bin/nightwatch --retries 1",
"cleanConfigFiles": "del 'config/*.conf.js'",
"cleanReports": "del 'reports/*'"
},
"author": "Alex",
"license": "ISC",
"dependencies": {
"allure-commandline": "^2.29.0",
"chromedriver": "^94.0.0",
"csvtojson": "^2.0.10",
"del": "^4.1.1",
"del-cli": "^5.0.0",
"nightwatch": "^2.2.3",
"nightwatch-allure": "^1.2.0",
"selenium-server": "^3.141.59",
"uuid": "^10.0.0",
"yargs": "^15.3.1"
}
}
I've run various commands:
npm install allure-commandline
npm install nightwatch-allure
allure generate ./allure-results --clean && allure open
allure --version
npm install -g allure-commandline
npm install -g nightwatch-allure
I've made sure there's an entry in System Variables for the location of \node_modules\allure-commandline\bin
I've tried deleting the node_modules folder and running npm install again
02 July, 2024
How do iI fix the error with UIViewControllerRepresentable?
I got the error on my visionOS app saying that my view doesn't conform to UIViewControllerRepresentable. I tried this code in another visionOS project and it works. Is there anything I can dp?
import SwiftUI
import AVKit
import UIKit
struct PlayerView: UIViewControllerRepresentable {
typealias UIViewControllerType = AVPlayerViewController
var url: String = "
https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8"
/>
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
// controller.navigationItem.hidesBackButton = true
// controller.showsPlaybackControls = false
controller.player = AVPlayer(url: URL(string: url)!)
controller.player?.playImmediately(atRate: 1.0)
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
class Coordinator: NSObject, AVPlayerViewControllerDelegate {
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
}
a prompt answer.....
import SwiftUI
import AVKit
import UIKit
struct PlayerView: UIViewControllerRepresentable {
typealias UIViewControllerType = AVPlayerViewController
var url: String = "
https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8"
/>
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
// controller.navigationItem.hidesBackButton = true
// controller.showsPlaybackControls = false
controller.player = AVPlayer(url: URL(string: url)!)
controller.player?.playImmediately(atRate: 1.0)
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
class Coordinator: NSObject, AVPlayerViewControllerDelegate {
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
}
a prompt answer.....
Unable to calculate pod specific utilization of the resource through PromQL
I am calculating the namespace specific resource utilization which includes request and resource for cpu and memory and also doing the same for pod specific data.
When I am trying to aggregate the data based on pod to namespace level it is not matching the data directly driven by namespace filter.
I want the pod specific data which matches the namespace data when got aggregated.
For namespace specific data I am using below four queries. (Which is giving me correct answer)
{"cpu_usage": f"sum_over_time(namespace:container_cpu_usage:sum{{namespace='{namespace}'}}[1d])",
"cpu_request":f"sum_over_time(namespace_cpu:kube_pod_container_resource_requests:sum{{namespace='{namespace}'}}[1d])",
"memory_usage":f"sum_over_time(namespace:container_memory_usage_bytes:sum{{namespace='{namespace}'}}[1d])",
"memory_request":f"sum_over_time(namespace_memory:kube_pod_container_resource_requests:sum{{namespace='{namespace}'}}[1d])"}
For pod specific data I am using below four queries. (When I aggregate this queries using sum (query) by (namespace) the result is not matching the above queries' readings.)
{"cpu_usage": f"sum_over_time(pod:container_cpu_usage:sum{{namespace='{namespace}'}}[1d])",
"cpu_request": f"sum_over_time(kube_pod_container_resource_requests{{namespace='{namespace}', resource = 'cpu'}}[1d])",
"memory_usage":f"sum(sum_over_time(container_memory_usage_bytes{{namespace='{namespace}', container!='POD', container!=''}}[1d])) by (pod)",
"memory_request": f"sum_over_time(kube_pod_container_resource_requests{{namespace='{namespace}', resource = 'memory'}}[1d])"}
tl;dr
I want the same data as I am getting for the whole namespace but I want to segregate the usage and request for the specific pods.
When I am trying to aggregate the data based on pod to namespace level it is not matching the data directly driven by namespace filter.
I want the pod specific data which matches the namespace data when got aggregated.
For namespace specific data I am using below four queries. (Which is giving me correct answer)
{"cpu_usage": f"sum_over_time(namespace:container_cpu_usage:sum{{namespace='{namespace}'}}[1d])",
"cpu_request":f"sum_over_time(namespace_cpu:kube_pod_container_resource_requests:sum{{namespace='{namespace}'}}[1d])",
"memory_usage":f"sum_over_time(namespace:container_memory_usage_bytes:sum{{namespace='{namespace}'}}[1d])",
"memory_request":f"sum_over_time(namespace_memory:kube_pod_container_resource_requests:sum{{namespace='{namespace}'}}[1d])"}
For pod specific data I am using below four queries. (When I aggregate this queries using sum (query) by (namespace) the result is not matching the above queries' readings.)
{"cpu_usage": f"sum_over_time(pod:container_cpu_usage:sum{{namespace='{namespace}'}}[1d])",
"cpu_request": f"sum_over_time(kube_pod_container_resource_requests{{namespace='{namespace}', resource = 'cpu'}}[1d])",
"memory_usage":f"sum(sum_over_time(container_memory_usage_bytes{{namespace='{namespace}', container!='POD', container!=''}}[1d])) by (pod)",
"memory_request": f"sum_over_time(kube_pod_container_resource_requests{{namespace='{namespace}', resource = 'memory'}}[1d])"}
tl;dr
I want the same data as I am getting for the whole namespace but I want to segregate the usage and request for the specific pods.
Amazon athena, presto sql :INVALID_FUNCTION_ARGUMENT: Cannot unnest type: varchar
Have some transaction data and the data looks like:
record_id labels
001 ['first_record','transfer']
002 ['withdraw', 'holiday']
003 ['direct','change_password','transfer']
004 ['change_password']
......
Labels column is of string type.
Tried to unnest labels column
select record_id, new_labels from transactions, UNNEST(labels ) as t(new_labels ) order by record_id, new_labels
but got following error
INVALID_FUNCTION_ARGUMENT: Cannot unnest type: varchar
Then tried to cast string to array then to the unnest
select record_id, cast(json_parse(labels) as array(varchar)) as labels from transactions
but got following error:
INVALID_CAST_ARGUMENT: Cannot cast to array(varchar). ['withdraw', 'holiday']
Then simply tried
select cast(['first_record','transfer']) as array(varchar)
it returned
mismatched input '['. Expecting:
record_id labels
001 ['first_record','transfer']
002 ['withdraw', 'holiday']
003 ['direct','change_password','transfer']
004 ['change_password']
......
Labels column is of string type.
Tried to unnest labels column
select record_id, new_labels from transactions, UNNEST(labels ) as t(new_labels ) order by record_id, new_labels
but got following error
INVALID_FUNCTION_ARGUMENT: Cannot unnest type: varchar
Then tried to cast string to array then to the unnest
select record_id, cast(json_parse(labels) as array(varchar)) as labels from transactions
but got following error:
INVALID_CAST_ARGUMENT: Cannot cast to array(varchar). ['withdraw', 'holiday']
Then simply tried
select cast(['first_record','transfer']) as array(varchar)
it returned
mismatched input '['. Expecting:
Laravel sending contact form getting 550 error
I am trying to send mail with a contact form. I cannot figure why I am getting this error below. If I submit it with any address it comes back with this error. If I put any email address on my server it goes through and sends. So I do not know where to research and fix it.
"Expected response code "250" but got code "550", with message "550-Sorry! This server is unable to send email from this domain: 550 gmail.com. Please try sending from a domain on this server."
MAIL_DRIVER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=465
MAIL_USERNAME=me@domain.com
MAIL_PASSWORD=......
MAIL_ENCRYPTION=ssl
Controller:
Namespace App\Http\Controllers;
use App\Notifications\ContactFormMessage;
use App\Http\Controllers\Controller;
use App\Http\Requests\ContactFormRequest;
use App\Recipient;
Class ContactController extends Controller
{
public function show()
{
return view('contact.index');
}
public function mailContactForm(ContactFormRequest $message, Recipient $recipient)
{
$recipient->notify(new ContactFormMessage($message));
return redirect()->back()->with('message', 'Thanks for your message! We will get back to you soon!');
}
}
Model recipient
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Recipient extends Model
{
use Notifiable;
protected $recipient;
protected $email;
public function __construct() {
$this->recipient = config('recipient.name');
$this->email = config('recipient.email');
}
}
Checked email settings and password. ran composer dump-autoload
"Expected response code "250" but got code "550", with message "550-Sorry! This server is unable to send email from this domain: 550 gmail.com. Please try sending from a domain on this server."
MAIL_DRIVER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=465
MAIL_USERNAME=me@domain.com
MAIL_PASSWORD=......
MAIL_ENCRYPTION=ssl
Controller:
Namespace App\Http\Controllers;
use App\Notifications\ContactFormMessage;
use App\Http\Controllers\Controller;
use App\Http\Requests\ContactFormRequest;
use App\Recipient;
Class ContactController extends Controller
{
public function show()
{
return view('contact.index');
}
public function mailContactForm(ContactFormRequest $message, Recipient $recipient)
{
$recipient->notify(new ContactFormMessage($message));
return redirect()->back()->with('message', 'Thanks for your message! We will get back to you soon!');
}
}
Model recipient
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Recipient extends Model
{
use Notifiable;
protected $recipient;
protected $email;
public function __construct() {
$this->recipient = config('recipient.name');
$this->email = config('recipient.email');
}
}
Checked email settings and password. ran composer dump-autoload
01 July, 2024
Packing, unpacking and storing parameter pack in a tuple in c++ 17
I have a function pointer and parameters, and I'd like to save these and potentially modify them and call the function with them.
I've seen parts of this answered however I'm unsure how a complete solution would look like, I apologize, but I don't really understand parameter packs, and how they relate to tuple.
Here's bits of my code that I'm trying to make work together:
I have this which is basically just calling the function, I think this can be used to save the call into the "callable" structure, to make an interface.
from this question:
C++ generic function call with varargs parameter
template
auto call(R(*function)(Args...), Args... args) -> typename std::enable_if::value, R>::type {
return function(args...);
}
template
void call(void (*function)(Args...), Args... args) {
function(args...);
}
And this structure which should store the parameters and the function pointer. (thanks to RaymondChen for pointing out how it should be correctly)
template
struct callable
{
R(*function)(Args...);
std::tuple params;
callable(Args... argv):
params(std::make_tuple(argv...))
{}
};
I'm still unsure how I would actually call back the function with the tuple, as far as I understand I should somehow turn the tuple back to Args... and then simply call it.
What I'm trying to achieve:
* Save a call to be used later on
* Create my own call and fill it with my own parameters, from a running app.
* Read out saved parameters to do some manner of debugging.
I've seen parts of this answered however I'm unsure how a complete solution would look like, I apologize, but I don't really understand parameter packs, and how they relate to tuple.
Here's bits of my code that I'm trying to make work together:
I have this which is basically just calling the function, I think this can be used to save the call into the "callable" structure, to make an interface.
from this question:
C++ generic function call with varargs parameter
template
auto call(R(*function)(Args...), Args... args) -> typename std::enable_if::value, R>::type {
return function(args...);
}
template
void call(void (*function)(Args...), Args... args) {
function(args...);
}
And this structure which should store the parameters and the function pointer. (thanks to RaymondChen for pointing out how it should be correctly)
template
struct callable
{
R(*function)(Args...);
std::tuple params;
callable(Args... argv):
params(std::make_tuple(argv...))
{}
};
I'm still unsure how I would actually call back the function with the tuple, as far as I understand I should somehow turn the tuple back to Args... and then simply call it.
What I'm trying to achieve:
* Save a call to be used later on
* Create my own call and fill it with my own parameters, from a running app.
* Read out saved parameters to do some manner of debugging.
Replace a record with a value zero when a specific number is not find with shellscript
I have a file as shown below, I'm taking the last number on the column $2 and counting how many records are there finishing from 0 to 9, but sometimes there is no record with 0 to 9 so I need to replace it with result zero. I mean when I don't have any record on $2 finishing with for example with number 2, I will put as a result number 2 --> 0
Input file example:
2022-11-17 05:00:02.327, MSG:86442, AppID:22
2022-11-17 05:00:10.829, MSG:81874, AppID:9
2022-11-17 05:00:14.143, MSG:81778, AppID:10
2022-11-17 05:00:16.365, MSG:81782, AppID:22
2022-11-17 05:00:25.010, MSG:82959, AppID:22
2022-11-17 05:00:30.647, MSG:58653, AppID:22
2022-11-17 05:00:40.852, MSG:58198, AppID:11
2022-11-17 05:00:45.104, MSG:89039, AppID:22
2022-11-17 05:00:45.221, MSG:83564, AppID:21
2022-11-17 05:01:00.618, MSG:34115, AppID:20
2022-11-17 05:01:02.692, MSG:86963, AppID:21
2022-11-17 05:01:02.927, MSG:81387, AppID:10
2022-11-17 05:01:04.826, MSG:82119, AppID:11
2022-11-17 05:01:04.926, MSG:82111, AppID:11
2022-11-17 05:01:04.945, MSG:82116, AppID:13
2022-11-17 05:01:00.618, MSG:59110, AppID:20
Output:
# awk -F ',' '{print $2}' test.log|cut -c 10-10|sort|uniq -c
1 0
1 1
2 2
2 3
2 4
1 5
1 6
1 7
2 8
3 9
I try as shown below, but I need to put zero to field where I don't have any records found in $2 at the end with 0 to 9:
2022-11-17 05:00:02.327, MSG:86442, AppID:22
2022-11-17 05:00:14.143, MSG:81778, AppID:10
2022-11-17 05:00:16.365, MSG:81782, AppID:22
2022-11-17 05:00:25.010, MSG:82959, AppID:22
2022-11-17 05:00:40.852, MSG:58198, AppID:11
2022-11-17 05:00:45.104, MSG:89039, AppID:22
2022-11-17 05:01:00.618, MSG:34115, AppID:20
2022-11-17 05:01:02.927, MSG:81387, AppID:10
2022-11-17 05:01:04.826, MSG:82119, AppID:11
2022-11-17 05:01:04.926, MSG:82111, AppID:11
2022-11-17 05:01:04.945, MSG:82116, AppID:13
2022-11-17 05:01:00.618, MSG:59110, AppID:20
Output expectation :
awk -F ',' '{print $2}' test.log|cut -c 10-10|sort|uniq -c
nuberofrecords N° from0 to 9
# awk -F ',' '{print $2}' test.log|cut -c 10-10|sort|uniq -c
nuberofrecords N°from0 to 9
1 0
1 1
2 2
**0 3**
**0 4**
1 5
1 6
1 7
2 8
3 9
Input file example:
2022-11-17 05:00:02.327, MSG:86442, AppID:22
2022-11-17 05:00:10.829, MSG:81874, AppID:9
2022-11-17 05:00:14.143, MSG:81778, AppID:10
2022-11-17 05:00:16.365, MSG:81782, AppID:22
2022-11-17 05:00:25.010, MSG:82959, AppID:22
2022-11-17 05:00:30.647, MSG:58653, AppID:22
2022-11-17 05:00:40.852, MSG:58198, AppID:11
2022-11-17 05:00:45.104, MSG:89039, AppID:22
2022-11-17 05:00:45.221, MSG:83564, AppID:21
2022-11-17 05:01:00.618, MSG:34115, AppID:20
2022-11-17 05:01:02.692, MSG:86963, AppID:21
2022-11-17 05:01:02.927, MSG:81387, AppID:10
2022-11-17 05:01:04.826, MSG:82119, AppID:11
2022-11-17 05:01:04.926, MSG:82111, AppID:11
2022-11-17 05:01:04.945, MSG:82116, AppID:13
2022-11-17 05:01:00.618, MSG:59110, AppID:20
Output:
# awk -F ',' '{print $2}' test.log|cut -c 10-10|sort|uniq -c
1 0
1 1
2 2
2 3
2 4
1 5
1 6
1 7
2 8
3 9
I try as shown below, but I need to put zero to field where I don't have any records found in $2 at the end with 0 to 9:
2022-11-17 05:00:02.327, MSG:86442, AppID:22
2022-11-17 05:00:14.143, MSG:81778, AppID:10
2022-11-17 05:00:16.365, MSG:81782, AppID:22
2022-11-17 05:00:25.010, MSG:82959, AppID:22
2022-11-17 05:00:40.852, MSG:58198, AppID:11
2022-11-17 05:00:45.104, MSG:89039, AppID:22
2022-11-17 05:01:00.618, MSG:34115, AppID:20
2022-11-17 05:01:02.927, MSG:81387, AppID:10
2022-11-17 05:01:04.826, MSG:82119, AppID:11
2022-11-17 05:01:04.926, MSG:82111, AppID:11
2022-11-17 05:01:04.945, MSG:82116, AppID:13
2022-11-17 05:01:00.618, MSG:59110, AppID:20
Output expectation :
awk -F ',' '{print $2}' test.log|cut -c 10-10|sort|uniq -c
nuberofrecords N° from0 to 9
# awk -F ',' '{print $2}' test.log|cut -c 10-10|sort|uniq -c
nuberofrecords N°from0 to 9
1 0
1 1
2 2
**0 3**
**0 4**
1 5
1 6
1 7
2 8
3 9
get-service needs local account - how to consolidate report
I have a list of computers and I can only use the local account (user1) for each computer to get a list of services. I'm looping through the computers and using get-service but as you can see I have to title each section with the computer name. I was wondering if I can consolidate this into one list with computer name attached to each service.
$computers =
@"
computer1
computer2
"@ -split [Environment]::NewLine
$computers | ForEach-Object {
$ServerUserId = "_$\user1"
$ServerPassword = ConvertTo-SecureString -String 'complexpassword' -AsPlainText -Force
$Credential = New-Object -TypeName PSCredential -ArgumentList $ServerUserId, $ServerPassword
Enter-PSSession -ComputerName $_ -Credential $Credential
"Computer name: $_"
get-service -ComputerName $computers -Name `
Service* `
Exit-PSSession
}
Output:
Computer name: Computer1
Service A
Service B
Computer name: Computer2
Service Y
Service Z
Would like it to look like:
Service A Computer1
Service B Computer1
Service Y Computer2
Service Z Computer2
$computers =
@"
computer1
computer2
"@ -split [Environment]::NewLine
$computers | ForEach-Object {
$ServerUserId = "_$\user1"
$ServerPassword = ConvertTo-SecureString -String 'complexpassword' -AsPlainText -Force
$Credential = New-Object -TypeName PSCredential -ArgumentList $ServerUserId, $ServerPassword
Enter-PSSession -ComputerName $_ -Credential $Credential
"Computer name: $_"
get-service -ComputerName $computers -Name `
Service* `
Exit-PSSession
}
Output:
Computer name: Computer1
Service A
Service B
Computer name: Computer2
Service Y
Service Z
Would like it to look like:
Service A Computer1
Service B Computer1
Service Y Computer2
Service Z Computer2
Adding Real Time Chat to Laravel Using Reverb & Vue
---
Laravel, the web artisan's favorite PHP framework, has just got a whole new powerful tool in its arsenal: Reverb. Among the official packages of Laravel, this WebSocket server application would seamlessly let you integrate real-time features in your Laravel-based applications, thereby taking interaction to a whole new level.
What is Laravel Reverb?
Reverb acts as a mediator between your Laravel-based application and its users. It establishes two-way, real-time communication based on WebSockets technology that allows web pages to receive updates on the server without a complete page refresh. This means that your users experience your application more dynamically and responsively.
Key Features of Laravel Reverb
Blazing Speed: Provides outstanding performance for real-time information with no lags.
Scalability: Grow with your applications to handle increased user traffic.
Seamless Integration: It works with broadcasting features added to Laravel and Laravel Echo to make development simple.
Push Updates: Push updates, messages, or events to clients to share your information instantly.
Built-in Security: Data encryption and authentication assurance for security communication
Adding Laravel Reverb to Your Chat Project
With Laravel Reverb, you can build dynamic chat applications. The messages are posted instantly, making users involved comprehensively. Here's a breakdown of the steps involved:
Step 1: Setting Up Your Laravel Project:
*
Ensure you have a Laravel application set up (version 11 or above is recommended).
*
If you're starting fresh, use composer create-project laravel/laravel your-chat-app-name.
Step 2: Install and Configure Reverb:
Install Laravel Reverb by running the following command:
php artisan install:broadcasting
Once you’ve installed Reverb, you can now modify its configuration from the config/reverb.php file. To establish a connection to Reverb, a set of Reverb “application” credentials must be exchanged between the client and server. These credentials are configured on the server and are used to verify the request from the client. You can define these credentials using the following environment variables:
BROADCAST_DRIVER=reverb
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
It also automatically creates echo.js in the resources/js directory.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'reverb',
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
});
Follow the Laravel documentation for configuration steps specific to your application server
https://laravel.com/docs/11.x/reverb
/>
Step 3: Running a Server
You can launch the Reverb server by using the reverb:start Artisan command:
php artisan reverb:start
By default, the Reverb server will be started at 0.0.0.0:8080, which makes it accessible from all network interfaces.
If you want to set a specific host or port, you can use the –host and –port options when starting the server.
php artisan reverb:start --host=127.0.0.1 --port=9000
You can also define REVERB_SERVER_HOST and REVERB_SERVER_PORT environment variables in your application’s .env configuration file.
Step 4: Setup Database
Open your .env file and adjust the settings to set up your database. Here’s an example using SQLite for simplicity:
DB_CONNECTION=sqlite
DB_DATABASE=/path/to/database.sqlite
You can create an SQLite database by simply running:
touch /path/to/database.sqlite
For this demo, we’ll create five predefined rooms. Let’s start by generating a model ChatMessage with migration for a chat_messages table.
php artisan make:model ChatMessage --migration
To make it simpler, only create name attributes for this model and migrate it.
Schema::create('chat_messages', function (Blueprint $table) {
$table->id();
$table->foreignId('receiver_id');
$table->foreignId('sender_id');
$table->text('text');
$table->timestamps();
});
php artisan migrate
Now, let's add the necessary relationships in the ChatMessage model. Open the ChatMessage.php file in the app/Models directory and update it as follows:
Laravel, the web artisan's favorite PHP framework, has just got a whole new powerful tool in its arsenal: Reverb. Among the official packages of Laravel, this WebSocket server application would seamlessly let you integrate real-time features in your Laravel-based applications, thereby taking interaction to a whole new level.
What is Laravel Reverb?
Reverb acts as a mediator between your Laravel-based application and its users. It establishes two-way, real-time communication based on WebSockets technology that allows web pages to receive updates on the server without a complete page refresh. This means that your users experience your application more dynamically and responsively.
Key Features of Laravel Reverb
Blazing Speed: Provides outstanding performance for real-time information with no lags.
Scalability: Grow with your applications to handle increased user traffic.
Seamless Integration: It works with broadcasting features added to Laravel and Laravel Echo to make development simple.
Push Updates: Push updates, messages, or events to clients to share your information instantly.
Built-in Security: Data encryption and authentication assurance for security communication
Adding Laravel Reverb to Your Chat Project
With Laravel Reverb, you can build dynamic chat applications. The messages are posted instantly, making users involved comprehensively. Here's a breakdown of the steps involved:
Step 1: Setting Up Your Laravel Project:
*
Ensure you have a Laravel application set up (version 11 or above is recommended).
*
If you're starting fresh, use composer create-project laravel/laravel your-chat-app-name.
Step 2: Install and Configure Reverb:
Install Laravel Reverb by running the following command:
php artisan install:broadcasting
Once you’ve installed Reverb, you can now modify its configuration from the config/reverb.php file. To establish a connection to Reverb, a set of Reverb “application” credentials must be exchanged between the client and server. These credentials are configured on the server and are used to verify the request from the client. You can define these credentials using the following environment variables:
BROADCAST_DRIVER=reverb
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
It also automatically creates echo.js in the resources/js directory.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'reverb',
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
});
Follow the Laravel documentation for configuration steps specific to your application server
https://laravel.com/docs/11.x/reverb
/>
Step 3: Running a Server
You can launch the Reverb server by using the reverb:start Artisan command:
php artisan reverb:start
By default, the Reverb server will be started at 0.0.0.0:8080, which makes it accessible from all network interfaces.
If you want to set a specific host or port, you can use the –host and –port options when starting the server.
php artisan reverb:start --host=127.0.0.1 --port=9000
You can also define REVERB_SERVER_HOST and REVERB_SERVER_PORT environment variables in your application’s .env configuration file.
Step 4: Setup Database
Open your .env file and adjust the settings to set up your database. Here’s an example using SQLite for simplicity:
DB_CONNECTION=sqlite
DB_DATABASE=/path/to/database.sqlite
You can create an SQLite database by simply running:
touch /path/to/database.sqlite
For this demo, we’ll create five predefined rooms. Let’s start by generating a model ChatMessage with migration for a chat_messages table.
php artisan make:model ChatMessage --migration
To make it simpler, only create name attributes for this model and migrate it.
Schema::create('chat_messages', function (Blueprint $table) {
$table->id();
$table->foreignId('receiver_id');
$table->foreignId('sender_id');
$table->text('text');
$table->timestamps();
});
php artisan migrate
Now, let's add the necessary relationships in the ChatMessage model. Open the ChatMessage.php file in the app/Models directory and update it as follows:








