CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

01 August, 2024

Make to make a file part of an OpenAI API chat conversation?

 Programing Coderfunda     August 01, 2024     No comments   

In ChatGPT, it easy to make files part of a chat conversation. I do this very often. I tell chatGPT to analyze a certain file. Based on the analysis, I ask questions about it. For example, I ask ChatGPT to analyze an invoice PDF. Chat GPT tells me what is in there. Then I ask if the calculations on it are correct. If that is fine, I ask if the invoice has regulatory compliance issues or is just fine and ready to be sent. Etc.


However, it is not clear how to do this with the OpenAI API. Text based chat is supported. That is clear to me. However, I want to "chat" about a (nontext/binary) file using the OpenAI API. It needs to be a "real" conversation, meaning that I need to be reply to reply to the answer to get more information.


Please let me know how to do this with python. Give me a real example.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

New SEO configuration package

 Programing Coderfunda     August 01, 2024     No comments   

Hey all,

I recently developed an SEO configuration package to simplify the process of configuring metadata.

This package has support for basic metadata, Twitter cards, Open Graph and JSON-LD Schema. You can also create your own metadata generators.

In addition, the package has 'expectations', which can be used to keep track of JSON-LD components as your graph is assembled from multiple location throughout your application.

You can find the package here:
https://github.com/Honeystone/laravel-seo

It would be great to get some feedback.

Cheers! submitted by /u/PiranhaGeorge
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Liqo installation issue

 Programing Coderfunda     August 01, 2024     No comments   

liqoctl install k3s


INFO Installer initialized

ERRO Error retrieving configuration: failed validating API Server URL "
https://127.0.0.1:6443": cannot use localhost as API Server address


shows this error but unable to solve


tried to change the server name but not working
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Clone git repository and install python packages in a shared folder path

 Programing Coderfunda     August 01, 2024     No comments   

I have a python project in a git repository and I am creating an azure pipeline to do the following tasks for that project:



* If git repository does not exist on a shared folder path, then clone it, else pull the last code.

* If virtual environment folder (.venv) does not exist on a shared folder path, then create and activate the virtual environment, else activate the current environment.

* Install python packages located in the file requirements.txt






This is my current YAML file to reach the previous steps:
trigger:
- main

pool:
vmImage: 'windows-latest'
name: 'On Premise Windows'
demands: Agent.Name -equals [Agent_name]

variables:
- group: Variable_Group
- name: PAT
value: $[variables.PAT]

steps:
- checkout: self
displayName: 'Checkout Repository'

- powershell: |
$parent_folder = '\\server\my\shared\folder\path'
$target_folder = Join-Path -Path $parent_folder -ChildPath '[project_name]'
$target_folder_exists = Test-Path -Path $target_folder
if ($target_folder_exists) {
cd $target_folder
git pull
} else {
git clone '
https://$(PAT)@dev.azure.com/my/git/project' $parent_folder
}
enabled: True
displayName: 'Clone or Pull Git repository'

- task: UsePythonVersion@0
inputs:
versionSpec: '3.11'

- powershell: |
$parent_folder = '\\server\my\shared\folder\path\[project_name]'
$target_folder = Join-Path -Path $parent_folder -ChildPath '.venv'
&requirements_path = Join-Path -Path $parent_folder -ChildPath 'requirements.txt'
$target_folder_exists = Test-Path -Path $target_folder
if ($target_folder_exists) {
cd &parent_folder
& C:\"Program Files"\Python311\python.exe -m venv .venv
}
pip install -r $requirements_path
displayName: 'Setup Python Environment and Install Dependencies'



The agent I am using is intalled On-Premise server and my shared folder path is located in an Azure VM. I am getting the following error:



========================== Starting Command Output =========================== "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo
-NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". '....'" fatal:
could not create leading directories of
'\server\my\shared\folder\path':
No such file or directory
##[error]PowerShell exited with code '1'. Finishing: Clone or Pull Git repository



It seems the On-premise server must have access to that shared folder path. Therefore, I have the following questions:



* Could On-premise server have access to the shared folder path if I give an user which has access to it? if so, how should I pass the user and password to access that path?. If not, what should be the proper way to achieve it?

* Is powershell a good approach to clone my repository and then to install the python packages? If not, what would be the rigth approach?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

31 July, 2024

How do I group segments of the data by emp_id, timein, timeout, and duration so that I can pick the one with the highest duration among the group?

 Programing Coderfunda     July 31, 2024     No comments   

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
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to find intersection of two ActiveRecord query results in Rails?

 Programing Coderfunda     July 31, 2024     No comments   

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.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Postgres CTE value not being used in where clause

 Programing Coderfunda     July 31, 2024     No comments   

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
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

zip the files and folders inside a parent directory without including the parent directory + Amazon Linux

 Programing Coderfunda     July 31, 2024     No comments   

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
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Multiply polars columns of number type with object type (which supports __mul__)

 Programing Coderfunda     July 31, 2024     No comments   

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?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

30 July, 2024

React's useState hook defined inside function component in TypeScript still gave error - Invalid hook call

 Programing Coderfunda     July 30, 2024     No comments   

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"
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Group by case where col A & col B = col B & col A, and then mutate column based on within-group similarity

 Programing Coderfunda     July 30, 2024     No comments   

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!
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Append dict to Chainmap during loop

 Programing Coderfunda     July 30, 2024     No comments   

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
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Error handling for Laravel's HTTP facade

 Programing Coderfunda     July 30, 2024     No comments   

submitted by /u/SjorsO
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What is the best VSCode extension for Testing in Laravel?

 Programing Coderfunda     July 30, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

29 July, 2024

Let's build a CMS with Filament 3 and Laravel 11 | 8 - Category SEO & Navbar improvements

 Programing Coderfunda     July 29, 2024     No comments   

submitted by /u/Tilly-w-e
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Deploy the laravel application in under 120 seconds using deployer

 Programing Coderfunda     July 29, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Has anyone used Turbolinks + Laravel to create a native hybrid app?

 Programing Coderfunda     July 29, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Supercharge your Laravel app with custom data types in PostgreSQL

 Programing Coderfunda     July 29, 2024     No comments   

submitted by /u/the_kautilya
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

My "Model Required Fields" package

 Programing Coderfunda     July 29, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

09 July, 2024

Quick tip about model serialization in event constructor

 Programing Coderfunda     July 09, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

08 July, 2024

How to find ceritain value in multiple section and return other value

 Programing Coderfunda     July 08, 2024     No comments   

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))
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

OpenCV - How to compute 3D points with SfM methods with known fundamental matrix

 Programing Coderfunda     July 08, 2024     No comments   

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.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to resolve a Cors error when trying to get an authentication token using authorisation code grant in Next.js

 Programing Coderfunda     July 08, 2024     No comments   

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
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

A laravel package to test/debug emails all at local machine

 Programing Coderfunda     July 08, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

.Net 8 XUnit: Use an In-Memory DBConnection for testing as a replacement for the real MySqlConnection

 Programing Coderfunda     July 08, 2024     No comments   

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
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

07 July, 2024

Pass multiple arguments to single command in custom position xargs

 Programing Coderfunda     July 07, 2024     No comments   

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
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Problemas com a biblioteca customtkinter

 Programing Coderfunda     July 07, 2024     No comments   

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)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Image not loading in HTML page when trying to change using GetElementByID method

 Programing Coderfunda     July 07, 2024     No comments   

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!
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Weekly /r/Laravel Help Thread

 Programing Coderfunda     July 07, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Livewire Filemanager

 Programing Coderfunda     July 07, 2024     No comments   

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]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • iOS 17 Force Screen Rotation not working on iPAD only
    I have followed all the links on Google and StackOverFlow, unfortunately, I could not find any reliable solution Specifically for iPad devic...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • Python AttributeError: 'str' has no attribute glob
    I am trying to look for a folder in a directory but I am getting the error.AttributeError: 'str' has no attribute glob Here's ...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • July (2)
  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda