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

06 February, 2024

Pass a button variable to controller codeigner 4

 Programing Coderfunda     February 06, 2024     No comments   

I tried passing a variable on a button into the controller, but when I tried to display the value it was always null


here is my code :
`id") . '" data-quotation="' . $row->id_quotation . '">Edit`



my ajax :
`$(document).on('click', '.edit', function() {
var quotation = $(this).attr('data-quotation');
$.ajax({
type: 'POST',
dataType: 'json',
url: baseurl + 'purchase/senddata/' + quotation,
data: {
'quotation': quotation
},
success: function(data) {
window.location = url;
}.then(function() {

})
});
});
`



this my Controller :
public function edit_data($id)
{
$id_quotation = $this->request->getVar('quotation');

$data = [
'title' => 'Edit Purchase Order',
'invoice' => $this->purchases->getPurchase($id),
'dataQuotation' => $this->purchases->getQuotationById($id_quotation)
];
dd($id_quotation);
return view('purchase-order/edit-data', $data);
}



and this my routes :
$routes-\>post('purchase/senddata/(:segment)', 'Purchase::edit_data/$1');



on my controller there I do a var_dump but the value is always null


from the way I tried to do it above can someone be kind enough to tell me where I made a mistake in my code
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Search Through exel file using a search html

 Programing Coderfunda     February 06, 2024     No comments   

function applyFilter(userInput){
/*
Use css to set the display to none first
*/
let allClientIDRows = document.querySelectorAll("ClientID-row > a");
for(let i = 0; i < allClientIDRows.length; i++){
let row = allClientIDRows[i]
let ClientID = row.getElementsByClassName("ClientID")[0]
if(allClientIDRows[i].textContent.trim() == userInput.trim()){
//You can also convert to lowercase for more accurate result
allClientIDRows[i].style.display = "inline";
}
}
}



This is the function that applys the filter to allow you to search and show what you search for and not the entire form.
i am only looking to show the searched item and not the entire spreadsheet



Data






Type in your ID















No ID FOUND






Loading








Failed to get data. Please refresh







function setErrorDisplay(loaderElm, allClientIDsElm, errorMessageElm){
loaderElm.style.display = "none"
allClientIDsElm.style.display = "none"
errorMessageElm.style.display = "block"
}

let allClientIDsElm = document.getElementById("allClientIDs")
let loaderElm = document.getElementById("loader")
let errorMessageElm = document.getElementById("errorMessage")

fetch("
{https://api.apispreadsheets.com/data/").then(res=>{ /> if (res.status === 200){
//sucess
res.json().then(data=>{
const yourData = data["data"]
for(let i = 0; i < yourData.length; i++){
let rowInfo = yourData[i]

let rowInfoDiv = document.createElement("div")
rowInfoDiv.classList.add("ClientID-row")

let rowClientID = document.createElement("h4")
let rowClientIDNode = document.createTextNode(rowInfo["ClientID"])
rowClientID.appendChild(rowClientIDNode)
rowClientID.classList.add("ClientID")

let rowRA = document.createElement("p")
let rowRANode = document.createTextNode(rowInfo["RA"])
rowRA.appendChild(rowRANode)
rowRA.classList.add("RA")

rowInfoDiv.appendChild(rowClientID)
rowInfoDiv.appendChild(rowRA)

allClientIDsElm.appendChild(rowInfoDiv)

}

loaderElm.style.display = "none"
allClientIDsElm.style.display = "block"
errorMessageElm.style.display = "none"

}).catch(err => {
setErrorDisplay(loaderElm, allClientIDsElm, errorMessageElm)
})
}
else{
setErrorDisplay(loaderElm, allClientIDsElm, errorMessageElm)
}
}).catch(err =>{
setErrorDisplay(loaderElm, allClientIDsElm, errorMessageElm)
})




This is the HTML part that runs the html search part


For some reason when i run with the function its still showing all the spreadsheet. What i am trying to do is How to make a search list in which element is only shown when user search for its exact value


when you type it shows you the result but the form will be empty untiil you type


i tryed with a search function with a filter but it shows the entire spreadsheet. Maybe i am doing something wrong or messed up somewhere in the code.


the applyfilter isnt working for me maybe there is another way i can do this
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Resources covering modern non-cloud (Laravel) deployment? Best practices for deploying updates, serving new features to beta-testers, reliable backups, security, etc.

 Programing Coderfunda     February 06, 2024     No comments   

Hey,

my background building Laravel apps is working on comparably small projects for a few clients that just needed more custom functionality than WordPress could offer and a handful of personal one-off projects for organizations I volunteer for. Mostly apps that you build and not touch anymore for long stretches of time.

Recently, someone approached me with a very interesting offer to develop a more complex application they'd use internally. Laravel seems suitable as no mobile app is required. Even down the road a progressive web app would totally suffice if necessary at all. Their business is on the smaller side of what can be considered a SMB, I'd estimate
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

My package Laravel, Lara Hierarchial Collections has been updated to support Laravel 11 - package to performantly convert a flat collection of hierarchical data to a nested collection for things like Org Charts.

 Programing Coderfunda     February 06, 2024     No comments   

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

Laravel Purity vs Spatie's laravel-query-builder?

 Programing Coderfunda     February 06, 2024     No comments   

I'm looking to implement an out-of-the-box solution for filtering & sorting results on my API endpoints, and I've come across Laravel Purity and Spatie's laravel-query-builder. Both are still actively being maintained and offer similar features. I like Purity's approach of defining the filter logic on the model instead of on the controller (which is what Spatie does), but Spatie's solution is a lot more popular.

Is there anyone who has tried both packages or prefers one over another for any good reason? submitted by /u/DigitalEntrepreneur_
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

05 February, 2024

How to know IP of the request made in python using amazon api gateway

 Programing Coderfunda     February 05, 2024     No comments   

I make a question explorer in python. To get IP ban I try to use amazon api gateway to rotate IP using this guide. But the problem is I can not configure to check the response actually goes through api gateway not used my IP. Please also suggest me to any modification required in the code. Any suggestion will be appreaciated.


The code I tried:

import requests
import xml.etree.ElementTree as ET
from requests_ip_rotator import ApiGateway, EXTRA_REGIONS

# Define Class
class QuestionsExplorer:
def GetQuestions(self, questionType, userInput, countryCode):
questionResults = []
# Build Google Search Query
searchQuery = questionType + " " + userInput + " "
# API Call
googleSearchUrl = "
http://google.com/complete/search?output=toolbar&gl=" + \
countryCode + "&q=" + searchQuery

# Call The URL and Read Data
result = session.get(googleSearchUrl)
tree = ET.ElementTree(ET.fromstring(result.content))
root = tree.getroot()
for suggestion in root.findall('CompleteSuggestion'):
question = suggestion.find('suggestion').attrib.get('data')
questionResults.append(question)

return questionResults

gateway = ApiGateway(site="
http://google.com",">
http://google.com", regions=["us-east-1"], access_key_id = "AWS_ACCESS_KEY_ID", access_key_secret = "AWS_SECRET_ACCESS_KEY")
gateway.start()
session = requests.Session()
session.mount("
http://google.com",">
http://google.com", gateway)

# use a Keyword for testing
userInput = "email marketing"

# Create Object of the QuestionsExplorer Class
qObj = QuestionsExplorer()
print("Keyword ideas about 'is'")
# Call The Method and pass the parameters
questions = qObj.GetQuestions("is", userInput, "us")

# Loop over the list and pring the questions
for result in questions:
print(result)
print("Keyword ideas about 'can'")
questions = qObj.GetQuestions("can", userInput, "us")

# Loop over the list and pring the questions
for result in questions:
print(result)

print("Done")
gateway.shutdown()
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

FindQt5.cmake in CMAKE_MODULE_PATH

 Programing Coderfunda     February 05, 2024     No comments   

I have started to practice Qt and now working on a mp3 file player and in order to do that I have to use a library called QtMediaPlayer and QMultiMedia.

find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)

find_package(Qt5 COMPONENTS Multimedia REQUIRED)

add_executable(MyMp3Player main.cpp mainwindow.cpp)

target_link_libraries(MyMp3Player Qt5::Multimedia)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How do i tweak my YAML file so that it builds but does not deploy? I want to set up a PR Build pipeline to test build each PR

 Programing Coderfunda     February 05, 2024     No comments   

See below for my YAML code that I have in Azure pipeline, it is based off of a pipeline I created that works great for building and deploying.


I'm hoping to create a new pipeline that triggers when there is a PR to the "main" branch, and it builds the branch in the PR to see if there are any build issues before we merge it with the "main" branch. I believe the name for this is Build Validation, but I'm stuck with creating the pipeline. Or is this right and I need to handle this with settings in the build validation setup?


I tried to update the YAML so it only runs when a PR is created, I think that part is okay. But I can't seem to figure out how to cancel the deployment part. The changes I make keep breaking in the build process of my existing normal pipeline.
name: Azure Static Web Apps CI/CD

pr:
branches:
include:
- main
trigger: none

jobs:
- job: build_and_deploy_job
displayName: Build and Deploy Job
condition: or(eq(variables['Build.Reason'], 'Manual'),or(eq(variables['Build.Reason'], 'PullRequest'),eq(variables['Build.Reason'], 'IndividualCI')))
pool:
vmImage: ubuntu-latest
variables:
- group: Azure-Static-Web-Apps
steps:
- checkout: self
submodules: true
- task: AzureStaticWebApp@0
inputs:
azure_static_web_apps_api_token: $(AZURE_STATIC_WEB_APPS)
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit:
https://aka.ms/swaworkflowconfig /> app_location: "/" # App source code path
api_location: "" # Api source code path - optional
output_location: "" # Built app content directory - optional
env:
NEXT_PUBLIC_OPENAI_KEY: $(NEXT_PUBLIC_OPENAI_KEY)

###### End of Repository/Build Configurations ######
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Reverb: First-party WebSocket server

 Programing Coderfunda     February 05, 2024     No comments   

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

Best practice for API versioning

 Programing Coderfunda     February 05, 2024     No comments   

Hello! I would like to ask how do you handle the versioning of your laravel API? Can you provide me some documentations on what best approach you follows? Thanks! submitted by /u/Environmental-Put358
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

04 February, 2024

How to get 30 days prior to current date?

 Programing Coderfunda     February 04, 2024     No comments   

I have a start calendar input box and an end calendar input box. We want defaults start calendar input box 30 days prior to current date and the end calendar input box to be the current date. Here is my date vars.

var today = new Date(),
dd = today.getDate(),
mm = today.getMonth(),
yyyy = today.getFullYear(),
month = ["January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October" "November", "December"],
startdate = month[mm] + ", " + yyyy.toString();




The end date would be something like var enddate = startdate - 30; Obviously this won't work.



So if the current date is December 30, 2011 I'd want the start date to read December 1, 2011.



EDIT: My question was answered... sort of. Date.today(); and Date.today().add(-30); work but I need the date in the format of January 13, 2012. Not Fri Jan 13 2012 10:48:56 GMT -055 (EST). Any help?



MORE EDIT: As of this writing it's 2018. Just use Moment.js. It's the best.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Correctly displaying parsed MJML in a Laravel mailable class

 Programing Coderfunda     February 04, 2024     No comments   

I'm using Spatie MJML package and this is what I have in my content() function of my LeadCreatedWelcomeMail class.
public function content()
{
$preview_text = 'Your Test Drive Has Been Scheduled!';
$lead = $this->lead;

$html = Mjml::new()->toHtml(view("emails.lead-created", compact('lead', 'preview_text'))->render());

return new Content(
view: $html,
);
}



The MJML correctly gets parsed as html. How can I pass it to my new Content class to display the email. The way I'm doing above is erroring out.


Error: View [the html strings that gets produced] not found.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Typescript eslint dont not recognize object in array

 Programing Coderfunda     February 04, 2024     No comments   

Hellow i got some problem with typescript or eslint (im new in eslint).


I show code, and next try to explain the error.


types.ts
export type TSettingsIputsState = {
personal: {
label: string;
name: keyof TApiResponseProfile;
value: string;
activeEdit: boolean;
onActionButtonClick: () => void;
}[];
display: boolean;
};



component.tsx
const [profileInputs, setProfileInputs] = useState();

useEffect(() => {
const setFormData = async () => {
if (!profileData) return;
const inputs = await inputsItems();

setProfileInputs({
personal: [
...inputs.personalSettings.map(({ label, name }) => ({
label,
name,
activeEdit: false,
value: profileData[name],
onActionButtonClick: () => console.log("asd"),
})),
],
display: false,
});
};

setFormData();
}, [profileData]);



This code give me no error from ts or eslint, but when i delete name and add dummy value, the ts dont suggest me to add name, and dont not recognize that dummy shouldn't be there.


Another error is when i change onActionButtonClick: (testing: string) => void in type there is no error when no change in onActionButtonClick: () => console.log("asd")


Please see image on link belowa


Why no error? doesn't suggest 'name'? IMAGE

https://i.stack.imgur.com/ppIAv.png />

tsconfig
{
"compilerOptions": {
"baseUrl": ".",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": false,
"strict": true,
"noEmit": true,
"target": "ES2015",
"esModuleInterop": true,
"module": "esnext",
"strictPropertyInitialization": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"sourceMap": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"noImplicitAny": false,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/layouts/*": ["./layouts/*"],
"@/complex/*": ["./components/complex/*"],
"@/parts/*": ["./components/parts/*"],
"@/inputs/*": ["./components/inputs/*"],
"@/forms/*": ["./components/forms/*"],
"@/hooks/*": ["./hooks/*"],
"@/skeletons/*": ["./components/skeletons/*"],
"@/utils/*": ["./utils/*"],
"@/middlewares/*": ["./middlewares/*"],
"@/providers/*": ["./providers/*"],
"@/types/*": ["./types/*"],
"@/apiTypes/*": ["./app/api/_types/*"],
"@/yupSchema/*": ["./yupSchema/*"],
"@/apiYupSchema/*": ["./app/api/_yupSchema/*"],
"@/dbPrisma": ["./utils/db.ts"],
"@/formsInitialValues/*": ["./formsInitialValues/*"],
"@/wretch": ["./utils/wretch"]

}
},
"include": ["next-env.d.ts", "types/**/*.ts", "app/_types/**/*.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}



eslintrc.json
{
"env": {
"browser": true,
"es2021": true,
"jest": true
},
"extends": [
"airbnb",
"airbnb-typescript",
"eslint:recommended",
"plugin:import/typescript",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"plugin:@tanstack/eslint-plugin-query/recommended"
],
"globals": {
"__dirname": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module",
"project": "./tsconfig.json"

},
"plugins": [
"react",
"react-hooks",
"@typescript-eslint",
"prettier",
"@kalimahapps/eslint-plugin-tailwind"
],
"rules": {
"react/react-in-jsx-scope": ["off"],
"no-unused-vars": ["off"],
"react/jsx-uses-react": ["off"],
"react/jsx-props-no-spreading": ["off"],
"react/function-component-definition": ["off"],
"react/no-unescaped-entities": ["off"],
"react-hooks/rules-of-hooks": ["error"],
"react-hooks/exhaustive-deps": ["warn"],
"react/no-array-index-key": ["off"],
"arrow-body-style": ["error", "as-needed"],
"import/extensions": ["off"],
"import/prefer-default-export": ["off"],
"import/no-extraneous-dependencies": ["off"],
"@kalimahapps/tailwind/sort": ["warn"],
"@kalimahapps/tailwind/multiline": ["warn"],
"@typescript-eslint/no-throw-literal": ["off"],
"jsx-a11y/click-events-have-key-events": ["off"],
"jsx-a11y/no-static-element-interactions": ["off"],
"no-return-await": ["off"],
"@typescript-eslint/return-await": ["off"],
"react/button-has-type": [
"off",
{
"button": true,
"submit": true,
"reset": true
}
],
"padding-line-between-statements": [
"error",
{ "blankLine": "always", "prev": "*", "next": "return" }
]
}
}




P.S.
It's only happend when personal is array, but the error with function parameter check persist anyway.


When i do this, and testing, typescript sugges ok, but not error on function parameter
personal: {
label: string;
name: keyof TApiResponseProfile;
value: string;
activeEdit: boolean;
onActionButtonClick: (testing: string) => void;
};



Can you guys/girls cam check if tsconfig or eslint have some bug?
Ty alot for your time
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Weekly /r/Laravel Help Thread

 Programing Coderfunda     February 04, 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

Java Thread: Real world Application Example

 Programing Coderfunda     February 04, 2024     No comments   

I was asked a question in an interview, where i have list available in the main method and and i was told there is some operation to be performed on each item in the list, how would i achieve this using threads concept.
Consider the following scenario:
I have a list of integers. I need to print all the values from the list. Can it be done using threads concept where i have multiple threads running on each item in the list and where each thread is used to print out a value rather than one thread printing all the values? I am not trying to modify any value in the list.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

03 February, 2024

"I'm running a cgo application in an Android environment, and it crashes at _cgo_topofstack. How can I troubleshoot this issue?"

 Programing Coderfunda     February 03, 2024     No comments   

"I'm running a cgo application in an Android environment, and it crashes at _cgo_topofstack.


How can I troubleshoot this issue?"
signal 11 (SIGSEGV), code -6 (SI_TKILL), fault addr --------
r0 00000000 r1 000028f3 r2 0000000b r3 00000008
r4 00002829 r5 92589500 r6 92589548 r7 0000010c
r8 00000007 r9 f2dda124 r10 92589400 r11 bc3218ca
ip bf21e9cc sp eeb7fc00 lr bb39d2f8 pc bb3c07d8

backtrace:
#00 pc 0049a7d8 /data/app/~~RaMB3k_xm7v41sDHB5G52Q==/com.tencent.supercar-Qe2_Smo7BnMcTvBrMSmgRA==/lib/arm/libtskm.so



enter image description here
# ./arm-linux-androideabi-addr2line result:
_cgo_topofstack
??:?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Pyomo error: No value for uninitialized NumericValue object

 Programing Coderfunda     February 03, 2024     No comments   

I'm a very new Pyomo user. I have been trying to find examples similar to my problem but I couldn't find any that were neither too easy or too difficult. It appears I have a problem initializing a variable but I can't figure out how to fix it. Here's my code:
`# Import of the pyomo module
from pyomo.environ import *

# Creation of a Concrete Model
model = ConcreteModel()

## Define sets ##
# Sets

model.I = RangeSet(1, N, doc='Farms')
model.J = RangeSet(1, n_max, doc='Turbines')
model.T = RangeSet(1, T, doc='Time horizon')
model.T_minus_1 = RangeSet(1, T-1, doc='Time horizon up to T-1')
model.R = RangeSet(1, R, doc='Maintenance Crews')

## Define variables ##
# Variables

model.Xpm_ijt = Var(model.I, model.J, model.T, domain=Binary, doc='Binary variable for shipment decision')
model.Xcm_ijt = Var(model.I, model.J, model.T, domain=Binary, doc='Binary variable for shipment decision')

model.y_rt = Var(model.R, model.T, domain=Binary, doc='Binary variable for shipment decision')
model.z_rit = Var(model.R, model.I, model.T, domain=Binary, doc='Binary variable for shipment decision')
model.f_ijt = Var(model.I, model.J, model.T, domain=Binary, doc='Binary variable for shipment decision')

model.a_ijt = Var(model.I, model.J, model.T, domain=NonNegativeIntegers, bounds=(0, H*10), doc='Operating time of turbine j at farm i at time t')

#Constraints
#Constraint 1

def init_a_ijt_rule(model, i, j, t):
if t == 1 and i == 1:
if j == 1:
return 0
elif j == 2:
return 0
elif j == 3:
return 10
elif j == 4:
return 20
elif j == 5:
return 23
elif t == 1 and i == 2:
if j == 1:
return 12
elif j == 2:
return 20
elif j == 3:
return 34
else:
return 0

model.constraint_a_ijt = Var(model.I, model.J, model.T, initialize=init_a_ijt_rule, doc='Operating time of turbine j at farm i at time t')

#Constraint 2

def operating_time_rule(model, i, j, t):
if model.Xpm_ijt[i, j, t].value == 1 or model.Xcm_ijt[i, j, t].value == 1:
return model.a_ijt[i, j, t+1] == 0
else:
return model.a_ijt[i, j, t+1] == model.a_ijt[i, j, t] + 1

model.constraint_operating_time = Constraint(model.I, model.J, model.T_minus_1, rule=operating_time_rule)

#Constraint 3

def PM_rule(model, i, j, t):
if value(model.a_ijt[i, j, t]) = H:
return model.Xpm_ijt[i, j, t] == 0
else:
return Constraint.Skip

model.constraint_Xpm = Constraint(model.I, model.J, model.T, rule=PM_rule)`



Until the 3rd constraint everything runs fine but I get this error when I run the PM_rule:


ERROR: evaluating object as numeric value: a_ijt[1,1,1] (object: ) No value for uninitialized NumericValue object a_ijt[1,1,1] ERROR: Rule failed when generating expression for Constraint constraint_Xpm with index (1, 1, 1): ValueError: No value for uninitialized NumericValue object a_ijt[1,1,1] ERROR: Constructing component 'constraint_Xpm' from data=None failed: ValueError: No value for uninitialized NumericValue object a_ijt[1,1,1]


I'm a new Pyomo user, so any help is welcome ! Thank you :)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Transform a blurhash to grayscale

 Programing Coderfunda     February 03, 2024     No comments   

Does anyone have an idea of how we can implement an efficient algorithm (js/ts) that given a blurhash string returns the equivalent (even of reduced quality) but in grayscale?


I need it because I use blurhashes as image holders, but in a part of my application I need to display images in black and white. Thanks in advance

---



EDIT


I managed to arrive at a code like this. the problem is that the blurhashes seem stretched and deformed compared to the originals
const WIDTH = 30;
const ASPECT_RATIO = validationConfig.media.profilePicture.aspectRatio;
const HEIGHT = Math.floor(WIDTH / ASPECT_RATIO);

export function convertBlurhashToGreyscale(blurhash: string) {

const pixels = decode(blurhash, WIDTH, HEIGHT);

for (let i = 0; i < pixels.length; i += 4) {
const grayValue = Math.round(
(pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3
);

pixels[i] = grayValue;
pixels[i + 1] = grayValue;
pixels[i + 2] = grayValue;
pixels[i + 3] = 255; // Imposta l'opacità a 255
}

const newHeight = Math.floor(WIDTH / ASPECT_RATIO);
return encode(pixels, WIDTH, newHeight, 4, 3);
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Breeze with PrimeVue

 Programing Coderfunda     February 03, 2024     No comments   

I just finished creating a Laravel Breeze equivalent starter kit using PrimeVue and PrimeFlex, the inspiration was to have a starter kit that would provide a larger selection of Vue components out of the box. Feedback is welcomed and appreciated!

I'm considering abstracting this into a composer package, but decided to see if there was any interest in the idea first. Perhaps a PrimeReact version as well?

You check it out here:
https://github.com/connorabbas/primevue-auth-starter

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

add values to the array object key by clicking the button with this value react

 Programing Coderfunda     February 03, 2024     No comments   

I have three buttons that when clicked I want to add a value to a selected field that is added dynamically:
const [Fields, setFields] = useState([
{ value: null, current: true },
{ value: null, current: false }
]);



value - is the key I want to add values to when the button is clicked


current - these keys store the state of the selected field when the field is clicked on
const [Fields, setFields] = useState([
{ value: null, current: true },
{ value: null, current: false }
]);

const GetSymbol = (event) => {
const symbol = event.currentTarget.dataset.value;
return symbol;
}
const InsertSymbol = (curField) => {
curField = GetSymbol;
return curField;
}

GetSymbol(event)} data-value="A">A
GetSymbol(event)} data-value="B">B
GetSymbol(event)} data-value="C">C

{Fields.map((field, i) => {
return (

{
setFields((oldArr) => {
let newArr = oldArr.map((item, index) => {
return {
...item,
current: index === i ? true : false,
};
});
return newArr;
});
}}
>
InsertSymbol(field.value)


);
})}



if the key current is true in the current field, then you must populate the values in field.value for that field.


I.e. If you click on A and B buttons, the value of field.value will be AB.
In my code, the functions GetSymbol and InsertSymbol are incorrect.


Please help me with this!
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

02 February, 2024

How to target the Nth element in a webcomponent shadowDOM with CSS ::part()

 Programing Coderfunda     February 02, 2024     No comments   

My is very simply built, a series of
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

MathML's msqrt not tall enough for fraction

 Programing Coderfunda     February 02, 2024     No comments   

I am new to MathML so please bear with me. I created the following equation:



A
B






But the results show the sqrt only over "A". I want it to be taller so it is over A and B.


I tried playing around with changing the css file, like margins and padding, but nothing seemed to work.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What's a better solution to tackle this problem - export / clone and restore for complex nested relations

 Programing Coderfunda     February 02, 2024     No comments   

You'll have to excuse the confusing title, I was trying to come up with a way to describe the many components to this challenge I'm trying to iterate on and come up with a better solution then the existing one.

Allow me to summarize. Our company provides an architecture design tool that, to simplify, allows customers to create projects, which contain architectures, which contain elements, interfaces, which contain requirements, tests, which contain.. etc etc. Lots and lots of nested relations. A project, after a few months usage, can easily contain thousands of records spanning two dozen tables, representing one-to-one, one-to-many and many-to-many relationships.

Currently all tables use an auto-increment numerical ids.. your standard stuff. Most tables also contain a project_id table which itself is just an integer.

Enter feature #1. The ability to export your project with all of its nested relations. This was simply enough.. we just load our project and recursively load all of its relationships, and then we just dump that whole thing as an array to a json file. This saves a full copy of the project with all of its relations represented by the values of thousands of primary keys at the time of export. Easy.

Enter feature #2. The ability to clone the above extremely complex project. Currently, we export the above, and then we have this complex script that iterates over every level of relation from the json dump and creates a new copy of everything. As it's doing this, it's storing all the reference primary ids from the json dump, and creating a relation map of sorts that it then uses to re-attach all the relations but using the new ids that are being created thanks to the auto-increment ids of the new copies.

Read that again if you must.. this one is a bit of a nightmare, this is not a piece of code I am happy with right now and is the constant source of issues. Before I describe what I think is a better way.. let's talk about the last feature.

Enter feature #3, the ability to restore a previous import (you can also think of these imports as a versioning system but not just for a single model but for a huge project). When you restore a project, you're overwriting the existing project and you must end up with the full working project with its thousand nested relations.

In a way, both cloning and restoring results in the same project state, but in the former case you end up with two projects where the cloned project will of likely diverge from the original, and in the case of restoring you still only have just the one project. I haven't done the restore feature yet.

Keeping in mind that the same database houses hundreds of these complex projects.. and each table having tens of thousands of records with different numerical ids that belong to different projects.

So restoring a project with the current system.. for example taking a project which at the time of export had 1000 nested records and now the current project has 3000, but after restoring we need to be back to 1000 (as an example).. this operation is quite a tricky one when using auto incrementing ids.

So voila.. this is the problem I'm currently facing. And I was just thinking aloud tonight of how to do this in a much better way.. and I'd love to hear all your thoughts about it before I talk about my new idea.

Really appreciate your thoughts actually : ) I don't come to Reddit often for coding problems but this one is a bigger task that's been on my mind a lot.

Oh and btw of course I'm using Laravel 10 here.

The first thought I had is that this could be dealt with with a NoSQL approach. But I kind of dread NoSQL and no way do i want to suggest that we move away from MySQL to something like Mongo at this time so we must stick to using a relational DB. I also don't want to use a different DB for each project. I am already dealing with 40+tables and having hundreds of dbs to manage would be a big nope.

The second thought I had is: use composite primary keys everywhere. Each project has a unique hash for a primary key and then everything else that is attached to it has a primary key that makes use of the project's unique key. Ignoring the pains and caveats that come with using composite primary keys.. this appears to make everything waaaaay easier. The export feature is the same as before. Cloning just involves creating a new project hash and then replacing it everywhere before inserting every records as is.. no need to relink things it just works and we just need to change one key.

And same for restoring.. we just wipe absolutely every record that contains the project key that's being restored and then we just restore the dump as-is.

Am I missing something or is this a waaay better solution?

The caveats with composite keys is that it can be less performant when making queries and it requires a lot of refactoring. Sometimes dependencies don't play well with composite keys.

I can't really think of another approach at the moment. What do you think about the composite key approach?

if you read this far.. I hope you're finding this mildly interesting! Thank you for making it this far and thanks a lot should you decide to share your wisdom developer to developer ;-)

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

Question regarding arrays and sequences in Java

 Programing Coderfunda     February 02, 2024     No comments   

I'm not sure on how to write this out in java code: "If the function is not null and the current index is less than the size, then the function array must agree with the field at the current index." It's listed as number six under wellFormed(). I just don't understand on how to check that the function array doesn't agree with the field at the current index, so i can throw a report. Thank you for the help !


This is the code that's relevant:




*
import java.util.function.Consumer;

/**

A Robot implemented with a dynamic array data structure

and providing "Sequence" capabilities. This is a homework assignment

inspired by Main: "Data Structures and Other Objects in Java" Chapter 3

(Sequence ADT). */



*
public class DynamicArrayPartSeq implements Robot, Cloneable { private static final int INITIAL_CAPACITY = 1;

// Data structure: Do not add or subtract from this: private String[] functions; private Part[] parts; private int size; private String function; private int currentIndex;

private static Consumer reporter = (s) -> System.out.println ("Invariant error: "+ s);

private boolean report(String error) { reporter.accept(error); return false; }

private boolean wellFormed() { // XXX: The invariant should be adjusted: no holes allowed // and it needs to check currentIndex and function

// 1. The "functions" and "parts" arrays must not be null.
// TODO
if (functions == null) {
return report("functions cant be null");
}
if (parts == null) {
return report("parts cant be null");
}

// 2. The "functions" and "parts" arrays are always the same length.
// TODO
if (functions.length != parts.length) {
return report ("functions and parts arrays should always bt the same length");
}

// 3. The size cannot be negative or greater than the length of the arrays.
// TODO
if (size < 0) {
return report ("size cant be negative");
}
if (size > functions.length) {
return report ("size can't be greater than functions length");
}
if (size > parts.length) {
return report ("size can't be greater than parts length");
}

// 4. None of the first “size” elements of either array can be null. (ie. no holes)
// TODO
if (size == 0) {
return report("first 'size' elements of either array cant be null");
}

// 5. The current index cannot be negative or greater than the size.
// TODO
if (currentIndex < 0) {
return report ("index cant be negative");
}
if (currentIndex > size) {
return report ("index cant be greater than the size");
}

// 6. If the function is not null and the current index is less than the size, then the
// function array must agree with the field at the current index.
// TODO
if (function != null && currentIndex < size) {

}

// If no problems discovered, return true
return true; }







I wrote out the first if regarding to check that the function isn't null and the current index is less than size. The second comment "function array must agree with the field at the current index" is throwing me off. I tried writing it as a second if statement inside the first, but I'm unsure on what to insert as the conditions.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

A simple statistic tool for Laravel apps

 Programing Coderfunda     February 02, 2024     No comments   

Hi folks,

a problem that I often face, when using analytic tools like Google Analytics oder Fathom Analytics is that they mostly show you data like visits, views, and page impressions. Everything beyond that, you need to integrate manually. That's why I started working on SimpleStats; it gives you KPIs like Reg, DAU, ARPU, ROI and much more out of the box, with a very simple installation!

The tool is not yet ready to launch and I don't know if anybody is interested in such a thing, but all tools I found out there, seem far to complicated to setup for me.

🚀 All you will need to do to get SimpleStats up and running is: Install a composer package, adjust the config to your needs, create an account, and add the token to your env file. Congrats, you're ready to analyze your campaigns and users!

📈 Here are a few of the KPIs that the tool provides: Registrations, Daily Active Users, New Active Paying Users, Average Revenue per User, Paying User, Revenue and much more. Everything filterable by date and UTMs!

🌟 Since the statistics tool and the composer client package are tailored precisely to Laravel, they can collect very interesting and important data without any additional complexity for you as the integrator of the package.

💻 Even though the composer client package is dedicated to Laravel, the API basically works with every client! So if you'd like to use the tool, even if you're not using Laravel, just trigger the API requests manually.

📍 Since the tool by default collects UTMs and Referrers for you and connects it with your users and their payments, it's super easy to see which of your marketing activities leads to revenue. You can simply analyze the ROI of your campaigns from the dashboard!

🛡️ We are fully committed to privacy compliance! No cookies are required or stored, ensuring your data remains confidential. You can rely on SimpleStats to respect your privacy and guarantee that your data will never be shared.

🏢 Collaborate by creating a team, inviting your co-workers to your projects, and assigning permissions to them. Each team is separated by tenancy, ensuring highly secure and robust data integration!

🎁 There will always be a free plan! If your business grows, you can support us with by subscribing. We would love to help you analyzing your campaigns. No need to enter credit card information at the registration.

​

📊 Feel free to checkout the current demo and hit that notify button to not miss the app launch:


https://simplestats.io

​

Thanks for reading.
I would love to here your feedback! submitted by /u/Nodohx
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

01 February, 2024

Function is not running as expected [duplicate]

 Programing Coderfunda     February 01, 2024     No comments   

I am a total novice with zero background in computer coding, teaching myself how to write code. I would be so grateful if someone who actually knows what they're doing would please be able to explain why my code below isn't working? Don't give me the solution, please. I want to know the reason why it's not doing what I expect it to do. Thank you so much in advance!
function getComputerChoice() {
return rock || paper || scissors, Math.floor(Math.random() * 3);
let rock = 0
let paper = 1
let scissors = 2
if (0) {
return "rock"
} else if (1) {
return "paper"
} else {
return "scissors"
}
}



I tried what I included above and I expected the log to bring up either rock, paper, or scissors but it's only bringing up the random number! I tried moving the variables to the beginning of the code but that made no difference in the results.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Why insertMany does not create ObjectIds in mongoose?

 Programing Coderfunda     February 01, 2024     No comments   

Currently I'm developing an APP using Node.JS and MongoDB. I'm trying to insert multiple documents with predefined _id s and some ObjectId arrays.
When I use insertMany all documents _id fields are strings instead of ObjectId. However when I use create and pass an array it works fine but instead of one query it performs separate query for each item of the array.


As it is obvious as the array grows it would be critical problem.


How can I use insertMany with the fields of type ObjectId instead of string?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

PHP 8.3 Performance Improvement with Laravel

 Programing Coderfunda     February 01, 2024     No comments   

Has anyone upgraded to PHP 8.3 and seen performance improvements? I'm curious to see how much improvement real-world apps get. According to these benchmarks they got a 38% improvement in requests/second.
https://kinsta.com/blog/php-benchmarks/ submitted by /u/ejunker
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Print from database using array but ignore certain columns on data

 Programing Coderfunda     February 01, 2024     No comments   

I have a code which copies a line of data and pastes it into another sheet as an array, if a cell has been marked which a particular value (x) & then prints.


At the minute it copies the entire line of data, however I need it to ignore certain cells along that line of data.
Sub AlterQuote()
Dim FormWks As Worksheet
Dim DataWks As Worksheet
Dim myRng As Range
Dim myCell As Range
Dim iCtr As Long
Dim myAddr As Variant
Dim lOrders As Long

Application.ScreenUpdating = False

Set FormWks = Sheets("Quote")
Set DataWks = Sheets("Quote Database")

myAddr = Array("G9", "G10", "G11", "G12", "C14", "C15", "C16", "C17", "C18", "C19", "C20", "C21", "B25", "C25", "D25", "E25", "F25", "G25", "H25", "I25", "H38", "I38", "B26", "C26", "D26", "E26", "F26", "G26", "H26", "I26", "H39", "I39", "B27", "C27", "D27", "E27", "F27", "G27", "H27", "I27", "H40", "I40", "B28", "C28", "D28", "E28", "F28", "G28", "H28", "I28", "H41", "I41", "B29", "C29", "D29", "E29", "F29", "G29", "H29", "I29", "H42", "I42", "I30", "H31", "H32", "H33", "H43", "I43", "H44", "H45", "H46", "D57", "D58", "D59", "D60")

With DataWks
Set myRng = .Range("B3", _
.Cells(.Rows.Count, "B").End(xlUp))
End With

For Each myCell In myRng.Cells
With myCell
If IsEmpty(.Offset(0, -1)) Then
Else

.Offset(0, -1).ClearContents

For iCtr = LBound(myAddr) _
To UBound(myAddr)
FormWks.Range(myAddr(iCtr)).Value _
= myCell.Offset(0, iCtr).Value
Next iCtr

End If
End With
Next myCell

MsgBox "quote can now be altered on Quote Sheet"

Application.ScreenUpdating = True

End Sub




I know it's within this line With DataWks Set myRng = .Range("B3", _ .Cells(.Rows.Count, "B").End(xlUp)) End With but I can't get it to work
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Numbers with either comma or dot as separator : handle in front or back ?

 Programing Coderfunda     February 01, 2024     No comments   

Hi

My app is used by users that are either using comma or dot as a decimal separator.

The laravel backend is expecting a DOT as a number separator, because of "number" rule in form requests, and because of mysql.

The frontend is a Vue SPA app.

I've tried to change the validator rule so numbers are both accepted as "dot" or "comma" serapated, but then the DB complains about comma numbers !

So, I was wondering what should be the best practice : should the frontend ensure that numbers containing comma are replaced with dots before sending the SAVE call, or should it be handled on backend ? submitted by /u/Napo7
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

  • Sitaare Zameen Par Full Movie Review
     Here’s a  complete Vue.js tutorial for beginners to master level , structured in a progressive and simple way. It covers all essential topi...
  • AI foot tracking model
    I am a student doing a graduation project. I urgently need to deal with this model (I am attaching a link). I've never worked with pytho...
  • Laravel Search String
      Laravel Search String is a package by   Loris Leiva   that generates database queries based on one unique string using a simple and custom...
  • Writing and debugging Eloquent queries with Tinkerwell
    In this article, let's look into the options that you can use with Tinkerwell to write and debug Eloquent queries easier. The post Wr...
  • Laravel - Installation
    For managing dependencies, Laravel uses   composer . Make sure you have a Composer installed on your system before you install Laravel. In t...

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 (69)
  • 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 (4)
  • 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