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

31 March, 2024

There are two solutions for one board, using different chips. But one of their i2c address is the same. How to resolve conflict in one dts?

 Programing Coderfunda     March 31, 2024     No comments   

Two chips A and B conflict with 0x62 on i2c bus 10. If A@62 and B@62 are configured on dts, Linux loads the driver of A. If B@62 is in front, it will load the driver of B. Whoever is in front will Which driver will be loaded, and is there any way to make the two chips compatible in one DTS.


i2cdetect -r -y 10
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- UU -- UU -- UU -- UU --
60: UU -- UU -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --


i2cdetect -r -y 9
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- 0c -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- 28 -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- 37 -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- UU 62 UU -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- UU -- UU UU -- --


Hardware can't modify the address. If two dts are used, there will be two firmwares, which is inconvenient.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to properly integrate against 3rd party services

 Programing Coderfunda     March 31, 2024     No comments   

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

Weekly /r/Laravel Help Thread

 Programing Coderfunda     March 31, 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

Positioning agent randomly within GIS space

 Programing Coderfunda     March 31, 2024     No comments   

I am looking to randomly position a fixed number of 'People' agents into my GIS space with regions. I currently have a table with a column for region and have identically named GIS regions in my GIS map.
Each 'Person' has a parameter 'region' which into which I map the value of the 'region' column in my table to. I then need to find some way to set the position of the agent to a random point inside the assigned region.


I have tried:
GISRegion myRegion = main.map.searchFirstRegion(region);
Point pt = myRegion.randomPointInside();
setXYZ( pt.x, pt.y, pt.z );



in the "On startup" field for my Person Agent but it seems that main.map.searchFirstRegion(region); does not do a good job of getting the correct region, as agents are distributed in places where there is no region (i.e in the sea):
Image


Ideally, I would like to use void setLocation(region) but setLocation takes in a Point or INode variable whereas the 'region' parameter is a string. Is there a way to search the list of regions by name for the matching region and return that region?
Thanks!
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Google Api

 Programing Coderfunda     March 31, 2024     No comments   

Hey Reddit community! 👋

I’m excited to share my latest project with you all: the Laravel Google Services Client! 🎉

🔗 GitHub Repository:
https://github.com/tomshaw/google-api submitted by /u/bigspacecraft
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

30 March, 2024

python valueerror : too many values to unpack

 Programing Coderfunda     March 30, 2024     No comments   

I am a python beginner . I was trying to run this code :

def main():
print ( " This program computes the average of two exam scores . ")
score1,score2 = input ("Enter two scores separated by a comma:")
average = (score1 + score2)/2.0
print ("The average of the score is : " , average )




when I summon the main() I got this ValueError :

ValueError: too many values to unpack (expected 2)




what is wrong with this code ?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

storing std::reference_wrapper into std::set

 Programing Coderfunda     March 30, 2024     No comments   

I was hoping infer std::reference_wrapper to MyType& automagically on bool operator
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Dijkstra’s Algorithm negative edges

 Programing Coderfunda     March 30, 2024     No comments   

How can I formally prove that Dijkstra’s algorithm doesn’t work with negative-weighted edges?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

expo DocumentPicker is not selecting any document

 Programing Coderfunda     March 30, 2024     No comments   

I am new to React native i have a problem withe the expo DocumentPicker for some reason the DocumentPicker does not select any file, and it always shows that Selected Document: None

import React, { useState } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import * as DocumentPicker from "expo-document-picker";

export default function App() {
const [document, setDocument] = useState(null);

const pickDocument = async () => {
const result = await DocumentPicker.getDocumentAsync({ type: 'application/pdf' });
if (result.type === "success") {
setDocument(result);
}
};

return (


Selected Document: {document ? document.name : "None"}



);
}

const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: 20,
},
paragraph: {
marginTop: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
});
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to get the json object with Typescript?

 Programing Coderfunda     March 30, 2024     No comments   

I am trying to get job by job_id via firebase rest api. I am getting this JSON result below. How i can rid of the 0 and get the object?


And Is there better way to get the job via firebase rest api?
This is my code:
{
"0": {
"category_id": 0,
"created_on": "Mar 29, 2024",
"description": "Dolor justo tempor duo ipsum accusam rebum gubergren erat. Elitr stet dolor vero clita labore gubergren. Kasd sed ipsum elitr clita rebum ut sea diam tempor. Sadipscing nonumy vero labore invidunt dolor sed, eirmod dolore amet aliquyam consetetur lorem, amet elitr clita et sed consetetur dolore accusam.",
"job_id": "TEL5UAVd5b3Q4jLY2aFfWs4QneMO",
"job_nature": "Full-time",
"location": "Gabrovo, Bulgaria",
"qualifications": [
"Rebum vero dolores dolores elitr",
"Elitr stet dolor vero clita labore gubergren",
"Dolor justo tempor duo ipsum accusam"
],
"salary": "$1500-$1900",
"title": "Marketing manager",
"user_id": "qDDuvTWL00N2sNXPhMy2rE0ZB8w2"
}
}

export class JobDetailComponent implements OnInit {
job = {} as Job;

constructor(
private apiService: ApiService,
private activeRoute: ActivatedRoute
) { }

ngOnInit(): void {
this.activeRoute.params.subscribe((data) => {
const id = data['jobId'];

this.apiService.getJob(id).subscribe((job) => {
this.job = job;
console.log(job)
});
});
}
}

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment.development';
import { Category } from './types/category';
import { Job } from './types/job';

@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }

getCategories() {
const { apiUrl } = environment;
return this.http.get(`${apiUrl}/categories.json`);
}
getJobs() {
const { apiUrl } = environment;
return this.http.get(`${apiUrl}/jobs.json`);
}
getJob(id: string) {
const { apiUrl } = environment;
return this.http.get(`${apiUrl}/jobs.json?orderBy="job_id"&equalTo="${id}"`);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

29 March, 2024

Boost Your Laravel Forge Productivity 🚀

 Programing Coderfunda     March 29, 2024     No comments   

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

Suppress default message of assert_eq! when custom message provided?

 Programing Coderfunda     March 29, 2024     No comments   

To my surprise, when I supply a custom message, it seems that assert_eq!'s default message is also printed out regardless.


Here I'm comparing some very long strs. So it is preferable not to clutter up the console but instead take a limited slice of each.
let left = tds.get_bulk_post_str();
let error_msg = format!("Bulk text is not what is expected: get_bulk_post_str() starts\n{}...\n\nExpected text starts\n{}...\n",
&left[0..20], &expected_bulk_text[0..20]);
// assert_eq! not used because assert_eq! apparently does not suppress its default message even when you supply a custom message!
// ... and in this case the default message is far too long.
// assert_eq!(left, expected_bulk_text, "{}", error_msg);

// instead, I think I'm forced to do something like this:
if left != expected_bulk_text {
panic!("{}", error_msg)
}



... is there any way of suppressing the default message?


If not, this seems a strange design choice, unlike any other language I know. Is it deliberate?


PS I'm aware the first 20 chars of each string might be identical. Obviously if I really wanted to go to town on this I'd have to examine both strings to find out the first case of difference, and just print corresponding slices from the middle.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Bidimensional splines, strictly increasing in one argument

 Programing Coderfunda     March 29, 2024     No comments   

I am working in R. I want to specify flexibly a function q(X,Y) where q is strictly increasing with respect to X (but not necessarily with respect to Y).
I want to use bidimensional splines but I don't know how to do (how to impose the monotonicity constraint in 2D).
So far, my method is to select several values of Y, and for each values of Y, I compute a monotone splines with respect to X. And then I interpolate to create the whole function q. But I wonder if it was possible to do all this in 1 step?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

firebase_storage/object-not-found. No object exists at the desired reference

 Programing Coderfunda     March 29, 2024     No comments   

I am trying to fetch images from firebase storage and display it in my flutter app but i am getting the error "No object exists at the desired reference". All the images are stored in the root directory. I have also changed the firebase rules to allow read and write without authentication.
This is my code.
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Wallpaper App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WallpaperScreen(),
);
}
}

class WallpaperScreen extends StatefulWidget {
@override
_WallpaperScreenState createState() => _WallpaperScreenState();
}

class _WallpaperScreenState extends State {
List imageUrls = []; // Store fetched image URLs

@override
void initState() {
super.initState();
fetchImages();
}

Future fetchImages() async {
try {
final storageRef = FirebaseStorage.instance.ref();
final result = await storageRef.listAll();

for (var item in result.items) {
try {
final url = await item.getDownloadURL();
setState(() {
imageUrls.add(url);
});
} catch (error) {
print("Error fetching URL");
}
}
} catch (e) {
print("Error fetching images: $e");
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Wallpapers'),
),
body: GridView.builder(
itemCount: imageUrls.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0,
),
itemBuilder: (BuildContext context, int index) {
return Image.network(
imageUrls[index], // Load image from URL
fit: BoxFit.cover,
);
},
),
);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Use Font Awesome icon as CSS content

 Programing Coderfunda     March 29, 2024     No comments   

I want to use a Font Awesome icon as CSS content, i.e.,

a:before {
content: "...";
}




I know I cannot use HTML code in content, so is it only images left?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

09 March, 2024

SNMP OID not supported in HP GEN11 but same supported in old HP GEN machines

 Programing Coderfunda     March 09, 2024     No comments   

In DL325 GEN11 DA most of the SNMP OID below returns no such oid available for GEN11 but same works and returns the value in GEN10/GEN10 Plus. What to do get those values ?




cpqSeCpuStatus :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.1.2.2.1.1.6
SNMPv2-SMI::enterprises.232.1.2.2.1.1.6 = No Such Instance currently exists at this OID
cpqDaCntlrCondition :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.2.1.1.6
SNMPv2-SMI::enterprises.232.3.2.2.1.1.6 = No Such Instance currently exists at this OID
cpqDaAccelCondition :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.2.2.1.9
SNMPv2-SMI::enterprises.232.3.2.2.2.1.9 = No Such Instance currently exists at this OID
cpqDaLogDrvStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.3.1.1.4
SNMPv2-SMI::enterprises.232.3.2.3.1.1.4 = No Such Instance currently exists at this OID
cpqDaLogDrvCondition :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.3.1.1.11
SNMPv2-SMI::enterprises.232.3.2.3.1.1.11 = No Such Instance currently exists at this OID
cpqDaPhyDrvStatus :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.5.1.1.6
SNMPv2-SMI::enterprises.232.3.2.5.1.1.6 = No Such Instance currently exists at this OID
cpqDaPhyDrvCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.5.1.1.37
SNMPv2-SMI::enterprises.232.3.2.5.1.1.37 = No Such Instance currently exists at this OID
cpqDaPhyDrvSmartStatus :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.5.1.1.57
SNMPv2-SMI::enterprises.232.3.2.5.1.1.57 = No Such Instance currently exists at this OID
cpqDaTapeDrvStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.9.1.1.8
SNMPv2-SMI::enterprises.232.3.2.9.1.1.8 = No Such Instance currently exists at this OID
cpqHeEventLogCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.11.2.0
SNMPv2-SMI::enterprises.232.6.2.11.2.0 = No Such Instance currently exists at this OID
cpqHeThermalSystemFanStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.4
SNMPv2-SMI::enterprises.232.6.2.6.4 = No Such Instance currently exists at this OID
cpqHeThermalCpuFanStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.5
SNMPv2-SMI::enterprises.232.6.2.6.5 = No Such Instance currently exists at this OID
cpqHeFltTolFanCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.7.1.9
SNMPv2-SMI::enterprises.232.6.2.6.7.1.9 = No Such Instance currently exists at this OID
cpqHeTemperatureCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.8.1.6
SNMPv2-SMI::enterprises.232.6.2.6.8.1.6 = No Such Instance currently exists at this OID
cpqHeFltTolPwrSupplyCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.9.1
SNMPv2-SMI::enterprises.232.6.2.9.1 = No Such Instance currently exists at this OID
cpqHeFltTolPowerSupplyCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.9.3.1.4
SNMPv2-SMI::enterprises.232.6.2.9.3.1.4 = No Such Instance currently exists at this OID
cpqRackCommonEnclosureFanCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.22.2.3.1.3.1.11
SNMPv2-SMI::enterprises.232.22.2.3.1.3.1.11 = No Such Instance currently exists at this OID


cpqRackPowerSupplyCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.22.2.5.1.1.1.17
SNMPv2-SMI::enterprises.232.22.2.5.1.1.1.17 = No Such Instance currently exists at this OID
cpqHeResilientMemCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.14.4
SNMPv2-SMI::enterprises.232.6.2.14.4 = No Such Instance currently exists at this OID
cpqNicIfLogMapStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.18.2.2.1.1.11
SNMPv2-SMI::enterprises.232.18.2.2.1.1.11 = No Such Instance currently exists at this OID
cpqFcaHostCntlrStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.16.2.7.1.1.4
SNMPv2-SMI::enterprises.232.16.2.7.1.1.4 = No Such Instance currently exists at this OID
cpqNicIfPhysAdapterStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.18.2.3.1.1.14
SNMPv2-SMI::enterprises.232.18.2.3.1.1.14 = No Such Instance currently exists at this OID
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Spring Security not working after API migration to Spring Boot 3

 Programing Coderfunda     March 09, 2024     No comments   

Software versions



* Spring Boot and dependencies: 3.2.2

* Spring Core : 6.1.3

* Spring Security 6.2.1

* Jetty Server: 11.0.20

* Languages: Java 17, Kotlin (Jetbrains Kotlin and Kotlin test library versions) 1.8.10






Below are modified code snippets for Jetty based Http Server Configuration, API Configuration and API Security Configuration which now uses a SecurityFilterChain instead of WebSecurityConfigurerAdapter.


Http Server Configuration
@Configuration
@EnableConfigurationProperties(ApiServiceProperties::class)
@ComponentScan("com......service")
@Import(value = [ApiSecurityConfig::class, WebFluxConfig::class])
class HttpServerConfig(var apiServiceProperties: ApiServiceProperties) {

/**
* Jetty Server Bean.
*/
@Bean
@SuppressWarnings("LongMethod")
fun jettyServer(
context: ApplicationContext,
springSecurityFilterChain: Filter,
mdcSetterFilter: MdcSetterFilter,
webContextFilter: WebContextFilter
): Server {
LOG.info(
"Starting Jetty server with " + ""
)

.. code removed ..

ServletContextHandler(server, "").apply {
val servlet = JettyHttpHandlerAdapter(WebHttpHandlerBuilder.applicationContext(context).build())
addServlet(ServletHolder(servlet), "/")

addFilter(FilterHolder(mdcSetterFilter), "/*", EnumSet.of(DispatcherType.REQUEST))
addFilter(FilterHolder(webContextFilter), "/*", EnumSet.of(DispatcherType.REQUEST))

// The ping endpoint should be unsecured, therefore ignored by the security filter
addFilter(
FilterHolder { request: ServletRequest, response: ServletResponse, chain: FilterChain ->
if (request is HttpServletRequest && request.requestURI != "/v1/ping") {
springSecurityFilterChain.doFilter(request, response, chain)
} else {
chain.doFilter(request, response)
}
},
"/v1/*",
EnumSet.of(DispatcherType.REQUEST)
)
}.start()

.. code removed ..

server.start()

LOG.info("Started Jetty server.")
return server
}

.. code removed ..
}



API Configuration
@Configuration
@ComponentScan(basePackages = [
"com......security",
"com......service"
])
@EnableConfigurationProperties(ApiServiceProperties::class)
@Import(HttpServerConfig::class)
class ApiServiceConfig : AbstractSpringBasedApplicationConfig()



API Security Configuration
@Configuration
@EnableWebSecurity
@ComponentScan("com......security", "com......service")
@EnableMethodSecurity(prePostEnabled = false, jsr250Enabled = true)
class ApiSecurityConfig(
private val restAuthenticationEntryPoint: RestAuthenticationEntryPoint,
private val restAuthenticationProvider: RestAuthenticationProvider
) {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http
.cors { }
.anonymous { it.disable() }
.httpBasic { it.disable() }
.formLogin { it.disable() }
.logout { it.disable() }
.csrf { it.disable() }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.exceptionHandling { it.authenticationEntryPoint(restAuthenticationEntryPoint) }
.authenticationManager { authentication -> restAuthenticationProvider.authenticate(authentication) }
.addFilterBefore(RestAuthenticationTokenFilter(), AnonymousAuthenticationFilter::class.java)
.authorizeHttpRequests { it.requestMatchers("/**").permitAll().anyRequest().authenticated() }
return http.build()
}

@Bean
fun corsConfigurationSource(): CorsConfigurationSource = UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration(
"/**",
CorsConfiguration().applyPermitDefaultValues().apply {
allowedMethods = listOf("POST", "GET", "PUT", "DELETE", "HEAD")
}
)
}
}



Custom authentication provider
@Component
class RestAuthenticationProvider(
private val securityServiceClient: SecurityServiceClient,
private val cryptoService: CryptoService
) : AuthenticationProvider {

/**
* Given a [token] and [verifiedTokenModel], return a new User with granted authorities.
*/
private fun createAuthenticatedUser(token: String, verifiedTokenModel: VerifiedTokenModel) = User
.withUsername(verifiedTokenModel.verifiedPrincipalModel.id)
.password(token)
.authorities(verifiedTokenModel.verifiedPrincipalModel.scopes.map { scope ->
SimpleGrantedAuthority("ROLE_${scope.toUpperCase()}")
})
.build()

/**
* Given a [verifiedTokenModel], create a JSON Web Token to represent the authorizations of the verified principal.
*/
private fun createJwt(verifiedTokenModel: VerifiedTokenModel) = cryptoService.createAuthToken(
.. code removed ..
)

override fun authenticate(authentication: Authentication): Authentication? =
(authentication as? RestAuthenticationToken)?.token?.let { token ->
try {
val verifiedTokenModel = securityServiceClient.verifyToken(token)
val user = createAuthenticatedUser(token = token, verifiedTokenModel = verifiedTokenModel)

RestAuthenticationToken(
.. code removed ..
jwt = createJwt(verifiedTokenModel = verifiedTokenModel)
)
} catch (e: ReplyException) {
.. code removed ..
}
}

.. code removed ..
}



Below is a comparison of the new and old code for security configuration (Spring Boot 2.6.2 and Spring Core 5.3.14)





Postman request always receives a 403 response





Logs (without permit all)
DEBUG c.a.e.d.api.v1.security.MdcSetterFilter : Setting MDC logging context.
DEBUG c.a.e.d.a.v1.security.WebContextFilter : Setting WebContext on message
DEBUG o.s.security.web.FilterChainProxy : Securing GET /v1/clients/*/brands
INFO c.a.e.d.api.v1.config.HttpServerConfig : Token ::
DEBUG o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code



I also tried passing it.requestMatchers("/**").permitAll().anyRequest().authenticated() in the call to authorizeHttpRequests() however that results in a different failure behavior


Logs (with permit all)
DEBUG c.a.e.d.api.v1.security.MdcSetterFilter : Setting MDC logging context.
DEBUG c.a.e.d.a.v1.security.WebContextFilter : Setting WebContext on message
DEBUG o.s.security.web.FilterChainProxy : Securing GET /v1/clients/*/brands
INFO c.a.e.d.api.v1.config.HttpServerConfig : Token ::
...
...
DEBUG o.s.w.s.adapter.HttpWebHandlerAdapter : [49377233] HTTP GET "/v1/clients/*/brands"
...
DEBUG s.w.r.r.m.a.RequestMappingHandlerMapping: [49377233] Mapped to com......service.ClientsApiController#listBrands(String, ServerHttpRequest)
DEBUG AuthorizationManagerBeforeMethodInterceptor: Authorizing method invocation ReflectiveMethodInvocation: public org.springframework.http.ResponseEntity com......service.ClientsApiController.listBrands(..); target is of class [com......service.ClientsApiController]

DEBUG AuthorizationManagerBeforeMethodInterceptor: Failed to authorize ReflectiveMethodInvocation: public org.springframework.http.ResponseEntity com......service.ClientsApiController.listBrands(...); target is of class [com......service.ClientsApiController] with authorization manager org.springframework.security.config.annotation.method.configuration.DeferringObservationAuthorizationManager@2323fe6a and decision AuthorityAuthorizationDecision [granted=false, authorities=[ROLE_READ_BRANDS]]
DEBUG s.w.r.r.m.a.RequestMappingHandlerAdapter: [49377233] Using @ExceptionHandler com......service.DefaultExceptionHandler#onThrowable(Throwable, ServerWebExchange)
DEBUG o.s.w.s.adapter.HttpWebHandlerAdapter : [49377233] Completed 403 FORBIDDEN




* Have tried multiple combinations of the security chain as suggested on several similar threads

* Added a few more log statements in security configuration code to capture these events and help understand how the new flow works

* DEBUG level log statements added inside the RestAuthenticationProvider.authenticate() are not showing up in the logs, indicating it is not getting invoked, and the flow is breaking before reaching that point.






However I suspect that the configured AuthenticationProvider (tried using authenticationProvider(..) earlier, but that did not work either) and AuthenticationManager are not getting plugged in the chain for some reason. Need help from the community in guiding me to set this up correctly. Thank you.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Implementing an equation involving integrals as a filter

 Programing Coderfunda     March 09, 2024     No comments   

This is a question that possibly borders on the intersection of the general usage of MATLAB and/or signal processing. Thought I would first ask the question in a MATLAB forum before trying signal processing.



So our lecturer read out his notes/paper and said the equation







could be implemented as a filter.



At first, it seemed difficult to follow the idea but when realizing that integration is same as finding areas under the curve which seems similar to applying a low pass filter so that only the portion of the signal under the threshold is allowed to pass through, it made a bit of sense. But how - meaning to say which function - can I use to implement the above equation? Do I need three filters or can I use just one? How do I use the terms preceding the integrals in the filter?



Thanks in advance
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

TypeScript Type on constructor to reference itself in extended class

 Programing Coderfunda     March 09, 2024     No comments   

This works but I was wondering if there is a better way of getting the constructor to know we want a UserEntity aka typeof this
class BaseEntity {
constructor(data: ) {
Object.assign(this, data);
}
}

class UserEntity extends BaseEntity {
name: string;
}

user = new UserEntity({name: 'Bar'});
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

The ultimate guide to creating a course platform with Vue 3 & Filament 3

 Programing Coderfunda     March 09, 2024     No comments   

Want to learn how to create a course platform, with filament 3, Vue 3 and Laravel 10? Tune into my series as we explore how to build a course platform.

This is an ongoing course with lessons published each day, I aim for 2-3 lessons a day to be published. submitted by /u/Tilly-w-e
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

08 March, 2024

How to I add the sum of 2 dice throw continuously in JS?

 Programing Coderfunda     March 08, 2024     No comments   

I'm doing a school project of a dice game, the player select a number between 6-9 and afterwards throw two dices. If the dices show the chosen number, its game over. But i cant get the sum to add upp after each throw, it just shows each specific throws sum.


Also, how do i get the program to understand that it's game over when the dices shows the "knockout" number?


let knockoutSiffra = 0;

const dices = document.querySelectorAll('.dice');
console.log(dices);

dices.forEach(bt =>{
bt.addEventListener('click', (e) =>{
knockoutSiffra = e.target.innerHTML;
console.log(knockoutSiffra)
})
})

document.getElementById('go')
.addEventListener('click', () => {

if(knockoutSiffra != 0){
choose.style.display = 'none'
play.style.display = 'block'
console.log('kör')
}

else{
console.log('välj ett nummer')

}

const showNumber = document.getElementById('showNumber');
showNumber.innerText = 'Ditt valda nummer är:' + " " + knockoutSiffra

})

// Slide 3

let lost = document.querySelector('.lost')
lost.style.display = 'none';

const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const result = document.querySelector('.dice-result');
const game = document.querySelector('.game');

let score = 0;

game.addEventListener('click', () => {
let d1 = GetRandomDice ();
let d2 = GetRandomDice ();

dice1.src = `Dice img/Dice-${d1}.png`;
dice2.src = `Dice img/Dice-${d2}.png`;

let sum = d1 + d2;
result.innerText = 'Antal poäng:' + " " + sum;

function GetRandomDice(){
return Math.ceil(Math.random() * 6);

}

})

This is just the last part of the HTML



Ditt valda nummer är:




Antal poäng:



Kasta tärningarna









Du förlorade!


Spela igen




Tried very much of different stuff but i can't get the code to work properly.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

PHP compare two arrays and output all with zero at different record

 Programing Coderfunda     March 08, 2024     No comments   

I have two arrays:



Array1:

ID: 1
ID: 2
ID: 3
ID: 4
ID: 5




Array2, with num value:

ID: 2, NUM: 200
ID: 4, NUM: 400




I want the output like: (adding zero if no record in array2)

ID: 1, NUM: 0
ID: 2, NUM: 200
ID: 3, NUM: 0
ID: 4, NUM: 400
ID: 5, NUM: 0




I am new to PHP, tried array_diff and array_intersect but not find the clue, could you please let me know how can I do that?



Thanks.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Using UPDATE ... SET arr[idx] = ... to aggregate rows into arrays

 Programing Coderfunda     March 08, 2024     No comments   

I currently have a database schema like the following table:
CREATE TABLE Measures(
expId SERIAL,
iteration INT NOT NULL,
value float4 NOT NULL,
PRIMARY KEY(expId, iteration)
);




So, a table of various measurements, repeated for n iterations.
Though, because we have more data than originally expected, I want to move to a new table layout that instead uses an array column, which overall gives better performance (already tested and benchmarked):
CREATE TABLE TmpMeasures(
expId SERIAL PRIMARY KEY,
values float4[] NOT NULL
);



My problem now is how to get the old data into the new format.
In the simplest case, the data may look something like this:
INSERT INTO Measures (expId, iteration, value)
VALUES
(1, 1, 1.1),
(1, 2, 2.1),
(1, 3, 3.1),
(2, 1, 1.2),
(3, 1, 1.3);



And conversion could be done with a two step process, roughly like this, to first create the array for an experiment, and then populate the iteration values:
INSERT INTO TmpMeasures(expId, values)
SELECT expId, '{}'::float4[]
FROM Measures
ON CONFLICT DO NOTHING;

UPDATE TmpMeasures tm
SET values[iteration] = m.value
FROM Measures m WHERE tm.expId = m.expId;



Though, my problem now is that the UPDATE actually only ever seems to take the first iteration, i.e., iteration = 1.
I am not quite understanding why that is the case.


I suspect, alternative approaches to values[iteration] would try to group by expId, and order by iteration and aggregate that into an array.


Unfortunately, the data isn't perfect, but iterations should line up.


So, the following seems to work, but it's extremely slow, and I don't quite understand why it's needed in the first place.
DO
$do$
BEGIN
FOR i IN 1..(SELECT max(iteration) FROM Measures m) LOOP
UPDATE TmpMeasures tm
SET values[i] = m.value
FROM Measures m
WHERE
tm.expId = m.expId AND
m.iteration=i;
END LOOP;
END
$do$;



Why does the "normal" update statement not suffice?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Integrating TypeScript with Inertia.js and Vue.js

 Programing Coderfunda     March 08, 2024     No comments   

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

Laravel Request Forwarder

 Programing Coderfunda     March 08, 2024     No comments   

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

07 March, 2024

How to Create a New Table from JSONB_ARRAY_ELEMENTS and JSONB_OBJECT_KEYS in Postgresql?

 Programing Coderfunda     March 07, 2024     No comments   

I am using the http extension in Postgresql, making a request, and getting a list of jsonb [{keys, values}] in a single column 'details' as a response.


It seems like there should be an easy way to create a new table from the keys and values.


Here is the request:
WITH sport_markets_api AS (
SELECT ((CONTENT::jsonb ->> 'data')::jsonb ->> 'sportMarkets')::jsonb AS details
FROM http_post(
'
https://api.thegraph.com/subgraphs/name/', /> '{"query": "{sportMarkets(first:2,skip:0,orderBy:timestamp,orderDirection:desc){id,timestamp,address,gameId,maturityDate,tags,isOpen,isResolved,isCanceled,finalResult,homeTeam,awayTeam }}"}'::text,
'application/json'))



I tried:

SELECT
jsonb_array_elements(details) ->> jsonb_object_keys(jsonb_array_elements(details))
FROM sport_markets_api




and was expecting a table with columns based on the keys.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Is there a way to set Horizon's timeout on a job class ?

 Programing Coderfunda     March 07, 2024     No comments   

I'm refactoring a class that records a (predefined length of) an audio stream using Symfony process and an OS executable file.

The way it used to work was the job was sent on a regular redis queue, and timeout would be set on the symfony process, effectively making the job run for the time it needed.

Now we want to send the job on a Horizon queue. The timeout is still set on the process, but Horizon's config has its own timeout value in the config. The problem is that the length of the recording will vary from case to case, with an average being 60 minutes, but we do have cases doing for multiple hours.

I could set it up to a very (very) long timeout, but I find it counterintuitive. Isn't there a way that I could specify the value for timeout on a job ? Otherwise, is setting a humongously long timeout the only logical way to do this ? submitted by /u/CouldHaveBeenAPun
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Group the ones that are the same and right next to each other in sql

 Programing Coderfunda     March 07, 2024     No comments   

table:






websit_id

updated_at

display_id







1222

03-06 06:00

apple





1222

03-06 08:00

apple





1222

03-06 10:00

carrot





1222

03-06 12:00

apple





1222

03-06 14:00

fig





1234

03-06 06:00

apple





1234

03-06 08:00

peach









I wanted to label the rows so that it groups the same display ID that are right next to each other but would not group them if there's something else in btw.
The desired outcome should be the following:






websit_id

updated_at

display_id

group_label







1222

03-06 06:00

apple

1





1222

03-06 08:00

apple

1





1222

03-06 10:00

carrot

2





1222

03-06 12:00

apple

3





1222

03-06 14:00

fig

4





1234

03-06 06:00

apple

1





1234

03-06 08:00

peach

2









I am using snowflake for this.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Async Initializers Swift MVVM not working

 Programing Coderfunda     March 07, 2024     No comments   

Hi cann someone help me I really have trouble to get these inits to work. Due to the Tasks im always getting yelled at by xcode the not all properties are initialized:
import Foundation
import FirebaseFirestore

class ChatViewModel: ObservableObject {

@Published var chat: ChatModel
@Published var opposingUser: User

init(oppUser: User) {
self.opposingUser = oppUser
Task {
if let fetchedChat = try? await fetchChat(oppUser: oppUser) {
self.chat = fetchedChat
}
}
}

init(chat: ChatModel) {
self.chat = chat
Task {
if let fetchedUser = try? await getOpposingUser(chat: chat) {
self.opposingUser = fetchedUser
}
}
}

@MainActor
func fetchChat(oppUser: User) async throws -> ChatModel? {
do {
let documents = try await Firestore.firestore()
.collection("conversations")
.whereField("users", arrayContains: UserService.shared.currentUser?.id ?? "error")
.whereField("users", arrayContains: oppUser.id)
.getDocuments()

for document in documents.documents {
guard let chatData = try? document.data(as: ChatModel.self) else {
print("[DEBUG fetchChat(oppUser: User)]: Error while converting Firebase Document to ChatModel ")
return nil
}

return chatData
}
} catch {
print("[DEBUG fetchChat(oppUser: User)]: \(error)")
throw error // Re-throw the error so it can be handled by the caller if needed
}
return nil
}

@MainActor
func getOpposingUser(chat: ChatModel) async throws -> User? {
do {
let opposingUid: String
if chat.users[0] == UserService.shared.currentUser?.id {
opposingUid = chat.users[1]
} else {
opposingUid = chat.users[0]
}

let document = try await Firestore
.firestore()
.collection("users")
.document(opposingUid)
.getDocument()

guard let opposingUserDoc = try? document.data(as: User.self) else {
// Handle the case where conversion to User fails
print("[DEBUG (getOpposingUser(chat: chatModel)]: Error while converting Firebase-Document to User ")
return nil
}

return opposingUserDoc

} catch {
print("[DEBUG (getOpposingUser(chat: chatModel)]: \(error) ")
throw error
}
return nil
}
}



I tried to "pre initilize" the variables with something like self.chat = ChatModel() but due to the nature of my Cahtmodel I can't init it without properties.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Herd for Windows

 Programing Coderfunda     March 07, 2024     No comments   

Super psyched for the launch of Herd for Windows. That is all.

​


https://preview.redd.it/4t22y3gulvmc1.png?width=627&format=png&auto=webp&s=806bbe46479290857bc29f17e853d68667e03639


https://herd.laravel.com/ submitted by /u/VaguelyOnline
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

06 March, 2024

How to type two variables that are correlated in TypeScript?

 Programing Coderfunda     March 06, 2024     No comments   

I have a structure ComboChartSpec with primary and secondary fields. I'm defining a util function to process this ComboChartSpec.


If I define it in this way, it works
function process1() {
const yAxisType = 'primary';
const otherYAxisType = 'secondary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
function process2() {
const yAxisType = 'secondary';
const otherYAxisType = 'primary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}



I want to merge these two functions. But I kept getting TS errors. How can I resolve it? Thanks!
function process(yAxisType: 'primary' | 'secondary') {
const otherYAxisType = yAxisType === 'primary' ? 'secondary' : 'primary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}

Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is not assignable to type 'ComboChartAxisEncoding'.
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is not assignable to type 'ComboChartSingleAxisEncoding'.
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is missing the following properties from type '{ primary: ComboChartSingleAxisSectionEncoding; secondary: ComboChartSingleAxisSectionEncoding; scale: QuantitativeScale; }': primary, secondaryts(2322)
index.ts(85, 3): The expected type comes from property 'y' which is declared here on type 'ComboChartEncodingMap'



See Minimal repro on TS playground 👈
export type ComboChartAxisEncoding = ComboChartSingleAxisEncoding | ComboChartDualAxisEncoding;

export type ComboChartSingleAxisEncoding = {
primary: ComboChartSingleAxisSectionEncoding;
secondary: ComboChartSingleAxisSectionEncoding;
scale: 'quantitative';
};
export type ComboChartSingleAxisSectionEncoding = {
fields: number[];
};
export type ComboChartDualAxisEncoding = {
primary: ComboChartDualAxisSectionEncoding;
secondary: ComboChartDualAxisSectionEncoding;
};
export type ComboChartDualAxisSectionEncoding = {
fields: number[];
scale: 'quantitative';
};

function process1(): ComboChartAxisEncoding {
const yAxisType: 'primary' | 'secondary' = 'primary';
const otherYAxisType: 'primary' | 'secondary' = 'secondary';

return { // this works
[yAxisType]: { fields: [] },
[otherYAxisType]: { fields: [] },
scale: 'quantitative',
};
}
function process2(yAxisType: T): ComboChartAxisEncoding {
const otherYAxisType = (yAxisType === 'primary' ? 'secondary' : 'secondary') as (T extends 'primary' ? 'secondary' : 'primary');

// this doesn't work. Note that in my case this function wraps lots of test cases and each of them has this structure.
// So, if I don't have to change the structure of the JS objects, and just need to change the types, it would be better.
return {
[yAxisType]: { fields: [] },
[otherYAxisType]: { fields: [] },
scale: 'quantitative',
};
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Receiving Incoming SMS post Android 8

 Programing Coderfunda     March 06, 2024     No comments   

Since android 8 the OS has placed may restrictions on how and when can the apps use Broadcast Receivers and Services.



* Background Service Limitations

* Broadcast Limitations






TL;DR: Starting Android 8 the OS will stop your Services and Broadcast Receivers except in some situations mentioned in above documents.


What is then a proper way to detect incoming sms? We can use WorkManager to manually query the SMS to check for new entries every 15 minutes. But what would be a way to get it instantly?


Also the official docs list the SMS_RECEIVE intent in the list of broadcasts that are exceptions to the above rules, but many have found that the receivers and services still get terminated and I have confirmed that by testing it myself.


There are some spend tracking apps out there that still do track the incoming sms regardless of the situation.


Would appreciate any inputs on the situation.


Thanks.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Logo puzzle I made for Laracon

 Programing Coderfunda     March 06, 2024     No comments   

I am just getting into Laravel, but a friend of mine that went to Laracon asked me to make him a thing to hand out at the Laracon in Nashville last year. It actually was a bunch of pieces and surprisingly difficult to figure out believe it or not. I thought I would share a picture of it. I'm out of these and they're not for sale as I sold my lasercutter. Just thought I'd share for that like this sorta thing.


https://preview.redd.it/mdeyzgg68smc1.jpg?width=1201&format=pjpg&auto=webp&s=6cb85cacca07a36125d7ee6b8db1f588f651bb01 submitted by /u/jeffjohnvol
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47

 Programing Coderfunda     March 06, 2024     No comments   

---



The Laravel team released v10.47 this week, which added the whereAll and whereAny methods to the query builder, the ability to use sorting flags with the Collection sortByMany method, and more.


This week will likely be the last release to the 10.x branch before Laravel 11’s release on Tuesday, March 12th, 2024. Laravel 10 will continue to receive bug fixes until August 6th, 2024, and security fixes until February 4th, 2025.


New whereAll and whereAny query builder methods




@musiermoore contributed a new whereAll and whereAny methods to the query builder, along with orWhereAll and orWhereAny methods. These new methods can search against multiple columns using or or and logic
// Before using `orWhere`
User::query()
->where(function ($query) use ($search) {
$query
->where('first_name', 'LIKE', $search)
->orWhere('last_name', 'LIKE', $search)
->orWhere('email', 'LIKE', $search)
->orWhere('phone', 'LIKE', $search);
});

// Using `whereAny`
User::whereAny(
[
'first_name',
'last_name',
'email',
'phone'
],
'LIKE',
"%$search%"
);



Here’s an example of using whereAll, in which all columns would need to match using AND:
$search = 'test';

User::whereAll([
'first_name',
'last_name',
'email',
], 'LIKE', "%$search%");

/*
SELECT * FROM "users" WHERE (
"first_name" LIKE "%test%"
AND "last_name" LIKE "%test%"
AND "email" LIKE "%test%"
)
*/



You can combine multiple like this using orWhereAll and orWhereAny methods.


Support Sort Option Flags on sortByMany Collections




Tim Withers contributed the ability to pass multiple sorting options to the Collection sortBy method. Before this update, you could accomplish this using multiple callables, but using PHP’s sorting flags:
// Pull Request before example
$this->campaigns = $campaigns
->with('folder', 'campaignCategory')
->get()
->sortBy([
fn ($a, $b) => str($a->folder?->name)->lower() str($b->folder?->name)->lower(),
fn ($a, $b) => str($a->campaignCategory->name)->lower() str($b->campaignCategory->name)->lower(),
fn ($a, $b) => str($a->name)->lower() str($b->name)->lower(),
])

// Using sorting flags
$this->campaigns = $campaigns
->with('folder', 'campaignCategory')
->get()
->sortBy(['folder.name', 'campaignCategory.name', 'name'], SORT_NATURAL | SORT_FLAG_CASE)



You can learn more about sorting flags from the sort function in the PHP manual.


Set $failOnTimeout on Queue Listeners




Saeed Hosseini contributed the ability to set the $failOnTimeout property on the queue job that indicates if the job should fail if the timeout is exceeded:
class UpdateSearchIndex implements ShouldQueue
{
public $failOnTimeout = false;
}



Release notes




You can see the complete list of new features and updates below and the diff between 10.46.0 and 10.47.0 on GitHub. The following release notes are directly from the changelog:


v10.47.0






* [10.x] Allow for relation key to be an enum by @AJenbo in
https://github.com/laravel/framework/pull/50311 />

* Fix for "empty" strings passed to Str::apa() by @tiagof in
https://github.com/laravel/framework/pull/50335 />

* [10.x] Fixed header mail text component to not use markdown by @dmyers in
https://github.com/laravel/framework/pull/50332 />

* [10.x] Add test for the "empty strings in Str::apa()" fix by @osbre in
https://github.com/laravel/framework/pull/50340 />

* [10.x] Fix the cache cannot expire cache with 0 TTL by @kayw-geek in
https://github.com/laravel/framework/pull/50359 />

* [10.x] Add fail on timeout to queue listener by @saeedhosseiinii in
https://github.com/laravel/framework/pull/50352 />

* [10.x] Support sort option flags on sortByMany Collections by @TWithers in
https://github.com/laravel/framework/pull/50269 />

* [10.x] Add whereAll and whereAny methods to the query builder by @musiermoore in
https://github.com/laravel/framework/pull/50344 />

* [10.x] Adds Reverb broadcasting driver by @joedixon in
https://github.com/laravel/framework/pull/50088 />






The post Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47 appeared first on Laravel News.


Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

compare file's date bash

 Programing Coderfunda     March 06, 2024     No comments   

I'm working on a tiny dropbox-like bash script, how can I compare the dates of 2 files and replace the old one(s) with the new one without using rsync
is there any simple way to process this?
can the SHA1 help me with knowing the newer?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

05 March, 2024

Cannot get TRUE when assigning report URL Param to a field

 Programing Coderfunda     March 05, 2024     No comments   

I have a param coming in from a URL.


It is seen on the report/dashboard side.


However when I try to assign this paramater to the field to use as a filter the resolution is always FALSE.


if


Filter_Field_In_DataSet = thepassed in parameter
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Running Python code in Docker gives: "/usr/bin/python3: can't find '__main__' module in 'test.py'"

 Programing Coderfunda     March 05, 2024     No comments   

So I'm trying to run this docker container
FROM ubuntu:latest

RUN apt update
RUN apt install software-properties-common -y
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt install python3-pip -y
RUN apt-get remove swig
RUN apt-get install swig3.0
RUN ln -s /usr/bin/swig3.0 /usr/bin/swig
RUN pip3 install auto-sklearn

# During debugging, this entry point will be overridden. For more information, please refer to
https://aka.ms/vscode-docker-python-debug /> ADD . /test.py
WORKDIR /
CMD ["python3", "test.py"]



and I get the error "/usr/bin/python3: can't find 'main' module in 'test.py'" from Docker Desktop. There are other posts similar to this on Stack Overflow, but I made the appropriate changes and it still doesn't seem to work. My Python code is quite simple
import pandas as pd
import autosklearn.classification as classification
import sklearn.model_selection as model_selection

if __name__ == "__main__":
def split_train_val(self, X: pd.DataFrame, y: pd.DataFrame):
X_train, X_val, y_train, y_val = model_selection.train_test_split(
X, y, test_size=0.25)
return X_train, X_val, y_train.to_frame(), y_val.to_frame()

model = classification.AutoSklearnClassifier(
time_left_for_this_task=3600,
ensemble_size=1,
ensemble_nbest=1,
)

dataset = pd.read_csv('data.csv')
dataset = dataset.iloc[:100]
X, y = dataset.drop(columns=[target_col]), dataset[target_col]
self.model.fit(X, y)

print(self.model.cv_results_)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Validation Provider Package

 Programing Coderfunda     March 05, 2024     No comments   

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

The Evolution of the Laravel Welcome Page

 Programing Coderfunda     March 05, 2024     No comments   

---



The release of Laravel 11 and Laravel Reverb will happen on Tuesday, March 12, 2024. Along with major updates to Laravel, we'll get a new welcome page when creating a new Laravel application with laravel new or composer.


I thought it would be fun to see how the welcome page has evolved over previous versions of Laravel. Whether you are new to the framework or have been around a while, there's something special about creating a new Laravel project and seeing that welcome screen!


Laravel 11




Laravel 11 will feature a light and dark theme, which looks gorgeous and inviting. It has a vibrant background, clean icons, and a welcoming feel that inspires creativity:


Laravel 11 welcome page (dark mode)



Laravel 11 welcome page (light mode)



Comparing Laravel 11 (top) to Laravel 10 (bottom)



Laravel 10




It's hard to believe that Laravel 10 was released a year ago on February 14, 2023. Over the last year, we've received countless amazing new features and quality-of-life updates. Here's what the welcome page looks like with a fresh Laravel 10 installation:


Laravel 10 welcome (dark mode)



Laravel 10 welcome (light mode)



Notably, the Laravel logo is centered and is only the logo mark. Laravel 9 and 8 had a left-aligned logo + Laravel text mark:


Logo mark changes between Laravel 8 and Laravel 10



Laravel 8




The welcome page featured in Laravel 8 was the first time we saw a significant change since Laravel 5.x. Laravel 8 was released on September 8, 2020, during the period of time Laravel released a major version every six months:


Laravel 8 dark mode featuring updated Laravel branding



Laravel 8 light mode featuring updated Laravel branding



Laravel's branding was technically updated around the Laravel 6 release. However, Laravel 8 was the first time the new logo was introduced on the welcome page. It featured four main areas/links: documentation, Laravel News, Laracasts, and prominent ecosystem links.


Laravel 5.5




Between Laravel 6 and 7, we didn't see any significant changes to the welcome page, but at some point in the 5.x releases, the welcome page included links to documentation, Laracasts, Laravel News, Forge, and GitHub:


Laravel 5.5 welcome page



Laravel 5.0




Laravel 5.0's landing page had the words "Laravel 5" and rendered a random inspiring quote using the Inspiring facade:

Laravel 5
{{ Inspiring::quote() }}




Laravel 5.0 welcome page



Bonus: Laravel 4.2




Laravel 4.2 had a minimal welcome page featuring a nostalgic logo (base64 image) and folder structure, which included this hello.php file, with the text, "You have arrived."


Laravel 4.2 hello page




The post The Evolution of the Laravel Welcome Page appeared first on Laravel News.


Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel 11 + Laravel Reverb will be released on Tuesday, March 12th.

 Programing Coderfunda     March 05, 2024     No comments   

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

04 March, 2024

My page won't load despite routes on Flask pointing to the right .html code

 Programing Coderfunda     March 04, 2024     No comments   

I have been bashing my head for a while here...


I am trying to make my index open a page (lessonplan.html) after hitting a button.


`This is the captions route on my deployed website:
@app.route('/captions', methods=['GET']) def captions(): global transcript_text, lesson # Declare transcript_text as a global variable youtube_link = request.args.get('youtube_link')
if youtube_link:
transcript_list = get_youtube_transcript(youtube_link)
transcript_text = ' '.join([item['text'] for item in transcript_list])

try:
openai.api_key = os.getenv("sk-xxx")
lesson_title, lesson = generate_lesson(transcript_text)
except Exception as e:
lesson_title = "Lesson Title Generation Error"
lesson = f"Error generating lesson: {str(e)}"

qr_code_filename = generate_qr_code(youtube_link)
return render_template('lessonplan.html', youtube_link=youtube_link, lesson_title=lesson_title, lesson=lesson, qr_code=qr_code_filename)



Now, this is my index:

Guide Maker body { font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; }
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}

h1 {
color: #333;
}

form {
display: flex;
flex-direction: column;
align-items: center;
}

label {
margin-top: 10px;
font-weight: bold;
color: #555;
}

input, select {
width: 100%;
padding: 8px;
margin-top: 5px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
margin-top: 15px;
}

button:hover {
background-color: #0056b3;
}

Welcome to the Guide Maker
Enter YouTube Link: Get Captions







And my lessonpage.html whch should open up as I hit the button





Lesson Generated






{{ lesson_title }}




Watch the video here:





{{ lesson | safe }}








Send




function sendMessage() {
// Your JavaScript code for sendMessage
}

// Rest of your JavaScript code...


Download PDF

Go Back









Instead of opening up, I just get:



http://website.xyz/%7B%7B%20url_for('captions')%20%7D%7D 404 (Not Found).


My folder structure is correct. When I deploy this locally, I have no problem whatsoever.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

FilamentPHP and Socialite

 Programing Coderfunda     March 04, 2024     No comments   

I have an upcoming project that I will be using Filamentphp for - curious if anyone has paired Socialite with it? The client uses Google Workspace for all their employees and it would be great if I could implement Oauth via Google.

If not, even if you've used just Socialite I'm interested in your experience as it will be my first time using it. submitted by /u/acjshook
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Phone Number Formatting, Validation, and Model Casts in Laravel

 Programing Coderfunda     March 04, 2024     No comments   

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

VS Code Extension for API Insights

 Programing Coderfunda     March 04, 2024     No comments   

---



Recently, at Treblle, we released a Visual Studio Code extension to work with our free developer tool, API Insights. After releasing this new tool, we wanted to look for ways developers building OpenAPI Specifications could benefit without stopping what they were doing.


So, for those who need to be made aware, API Insights is a free developer tool we created at Treblle that lets you get insights into your API design. It will score your OpenAPI Specification against:



* Performance

* Quality

* Security






The way this works is that we analyze your specification to understand what this API does. We then compare your API to a set of industry standards for APIs and see how close you are to having an "industry standard API".


However, we go a step further than just analyzing your specification; we send a request to the first endpoint that could be successful and measure load time and response size. We can analyze something similar to understand your API better.


The VS Code extension will allow you to analyze your specifications without leaving your editor. Even better, though, is that it will then watch this file for changes and prompt you to re-run the analysis if a change is detected.


We wrote about this new free tool in a little more detail on our blog and would love to hear your thoughts about the extension - also, what developer tool you would find helpful! You never know; we may build it.



The post VS Code Extension for API Insights appeared first on Laravel News.


Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Phone Number Formatting, Validation, and Model Casts in Laravel

 Programing Coderfunda     March 04, 2024     No comments   

---



The Laravel-Phone package makes working with phone numbers in PHP and Laravel a breeze, offering validation rules, attribute casting, utility helpers, and more.


Have you ever built validation around phone numbers that supports multiple countries? This package has helpful validation rules built in, which makes it easy to validate numbers for any country. You can specify acceptible country code formats, but at the same time accept valid "international" numbers:
// Validate either USA or Belguim
Validator::make($request->all(), [
'phone_number' => 'phone:US,BE',
]);

// Validate US specifically, but also accept other countries
Validator::make($request->all(), [
'phone_number' => 'phone:US,INTERNATIONAL',
]);

// Use the Phone rule
Validator::make($request->all(), [
'phone_number' => (new Phone)->country(['US', 'BE']),
]);

// Match country code against another data field
Validator::make($request->all(), [
'phone_number' => (new Phone)->countryField('custom_country_field'),
'custom_country_field' => 'required_with:phone_number',
]);



This package uses the PHP port of Google's phone number handling library under the hood, which has robust parsing, formatting, and validation capabilities for working with phone numbers in PHP:
// Formatting examples

$phone = new PhoneNumber('012/34.56.78', 'BE');

$phone->format($format); // Custom formatting
$phone->formatE164(); // +3212345678
$phone->formatInternational(); // +32 12 34 56 78
$phone->formatRFC3966(); // +32-12-34-56-78
$phone->formatNational(); // 012 34 56 78



You can learn more about this package, get full installation instructions, and view the source code on GitHub. I recommend getting started with the readme for full documentation about this package.



The post Phone Number Formatting, Validation, and Model Casts in Laravel appeared first on Laravel News.


Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

03 March, 2024

Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive - Angular reactive forms

 Programing Coderfunda     March 03, 2024     No comments   

I have the following template. I'm trying to get to grips with reactive forms but am having a problem.





First Name*









Then in my component I have:
@Component({
selector: 'guest-input',
templateUrl: './guest-input.component.html',
})
export class GuestInputComponent implements OnInit {
@Input()
guest: Guest;

guestForm: FormGroup;

constructor(private _fb: FormBuilder) { }

ngOnInit() {
this.guestForm = this._fb.group({
firstname: ['test', [Validators.required, Validators.minLength(3)]]
});
}
}



This all looks fine to me but for some reason I am getting:



Error: Uncaught (in promise): Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).



I thought I had declared this in my .
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Weekly /r/Laravel Help Thread

 Programing Coderfunda     March 03, 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

How to add variation stock status to Woocommerce product variation dropdown

 Programing Coderfunda     March 03, 2024     No comments   

I would like to show the stock status (eg. In Stock / Out of Stock) for each product variation shown in the drop down list of variations on the Woocommerce Product Page. I have copied the relevant function to my theme's functions.php file, and can edit the content, but am unsure how to pull out the required stock status for each variation.



// Updated Woocommerce Product Variation Select

if ( ! function_exists( 'wc_dropdown_variation_attribute_options' ) ) {

/**
* Output a list of variation attributes for use in the cart forms.
*
* @param array $args
* @since 2.4.0
*/

/*

function wc_dropdown_variation_attribute_options( $args = array() ) {
$args = wp_parse_args( apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args ), array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __( 'Choose an option', 'woocommerce' ),
) );

$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute'];
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
$id = $args['id'] ? $args['id'] : sanitize_title( $attribute );
$class = $args['class'];
$show_option_none = $args['show_option_none'] ? true : false;
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' ); // We'll do our best to hide the placeholder, but we'll need to show something when resetting options.

if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
$attributes = $product->get_variation_attributes();
$options = $attributes[ $attribute ];
}

$html = '';
$html .= '' . esc_html( $show_option_none_text ) . '';

if ( ! empty( $options ) ) {
if ( $product && taxonomy_exists( $attribute ) ) {
// Get terms if this is a taxonomy - ordered. We need the names too.
$terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );

foreach ( $terms as $term ) {
if ( in_array( $term->slug, $options ) ) {
$html .= 'slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) ) . ' ';
}
}
} else {
foreach ( $options as $option ) {
// This handles lt 2.4.0 bw compatibility where text attributes were not sanitized.
$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );

$html .= '' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . ' Output Stock Details Here ';
}
}
}

$html .= '';

echo apply_filters( 'woocommerce_dropdown_variation_attribute_options_html', $html, $args );
}
}





I can pull out the stock level for the overall product, but now for each variation.



Any help would be greatly appreciated.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to get rid of the padding of SF Symbol in SwiftUI

 Programing Coderfunda     March 03, 2024     No comments   

In example, I have a simple SwiftUI code that has an SF Symbol yet without any paddings. Here, I'm using .scaledToFit, so the image would be edge to edge (in future I'm gonna apply padding to it).
VStack{
Image(systemName: "drop")
.resizable()
.font(.largeTitle.weight(.ultraLight))
.scaledToFit()
}




Screenshot shows a small gap on the right side:





After using additional padding, the image still looks off. That gap becomes less but it's still noticable.


My expectation was that applying .scaledToFit would actually scale the image to fit the screen, and then I could use the padding.


Though even with padding the issue persists:





I tried to use .aspectRatio(contentMode: .fit), and also different aspect ratios hoping that it could fix it.


Also the same issue persists even using the "square" SF Symbol (that likely excludes aspect ratio issue cuz square is 1:1) Though I fixed issue with square using .imageScale(.large)


Square without .imageScale(.large):





Square with .imageScale(.large):
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Watch Face isn't recognised as a standalone app by Google Play store

 Programing Coderfunda     March 03, 2024     No comments   

I am developing a watch face using the Watch Face Format. My watch face consists of a Wear OS bundle (the watch face itself) and an optional companion app for the mobile phone.


I have set my watch face to be a standalone app (following the instructions from the
https://developer.android.com/training/wearables/apps/standalone-apps) by setting the com.google.android.wearable.standalone meta data in the manifest.xml:










However, for some reason Google Play still thinks that the Wear OS bundle is a non-standalone app (see the "Requires mobile app" message in the screenshot below).


Has anyone experienced a similar issue? Do you guys have any ideas what could be wrong?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

02 March, 2024

What's the go to method on doing Auto Scaling with Laravel?

 Programing Coderfunda     March 02, 2024     No comments   

I'm only familiar with using Elastic Beanstalk and ECS with docker to do auto scaling.

Is there a better way in doing this? I'm mostly looking into making it easier to deploy code updates.

In your work, how do you do auto scaling with Laravel? submitted by /u/mod_suck
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Why is there a gap to other elements when I add an image to the navigation bar in html?

 Programing Coderfunda     March 02, 2024     No comments   

right now the HTML file gives me very weird issue when the image is added. When I remove the image, it returns to normal. I want to make the element alignment matches with the image.





Here is the HTML file:






DataPredict













Home





Contact





Why DataPredict












And here is the CSS file:
body {

margin: 0px 0px 0px 0px;

}

.top-navigation-bar {

background-color: #5B9BD5;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
width: inherit;
height: 50px;

}

.top-navigation-bar img{

margin: 0px;
padding: 0;
border-width: 0;
width: auto;
height: 100%;
display: inline;

}

.top-navigation-bar button{

border-width: 0px;
margin: 0px;
padding: 0;
background-color: inherit;
padding-block: 0;
width: 10%;
height: 100%;
border-style: none;
display: inline;

}

.top-navigation-bar button text{

padding: 0;
height: 100%;
width: 95%;
background-color: inherit;
display: inline;

}

.top-navigation-bar button selected{

padding: 0;
height: 90%;
width: 5%;
background-color: inherit;
display: inline;

}

.top-navigation-bar button:hover selected{

padding: 0px 0px 0px 0px;
height: 90%;
width: 5%;
background-color: black;
display: inline;

}



Ah also, I was trying to make a black bar appear when the mouse hovers over it. So don't change that. But also I could not get that to work either, since it isn't appearing when I hover it. What exactly I'm missing here?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Drop down menu with protected sheet

 Programing Coderfunda     March 02, 2024     No comments   

I need your help.
I have a little file Excel.
This file has protected sheets with drop down menu and these are the steps:


1)double click to show Userform1;
2)click on CommandButton of the Userform to write on the protected sheet:
Private Sub CommandButton1_Click()
ActiveSheet.Unprotect Password:="password"

Range("a1") = "prova"

ActiveSheet.Protect Password:="password", DrawingObjects:=True

Unload Me
End Sub



The problem is that when I fix manually protected sheets, double click on cells with drop down menu does work, but after I execute the "Private Sub CommandButton1_Click()" procedure, drop down menu doesn't work any more.
Is it possible to force drop down menu to work also after I execute the procedure triggered by CommandButton1?
I need Userform1 to show after double-click event, also for the cells formatted with the drop down menu.


Thank you in advance


I tried changing parameters of the Protect Method, but with the same result.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Switching between two frames on seperate files in tkinter

 Programing Coderfunda     March 02, 2024     No comments   

I am writing a program where I have the opportunity, to switch between two frames which are one two separate Files. The main file is called "Main_Menu" while the other file is called "first_page". When I import the classes from both classes into each other, then I get an circular import which leads to the program not working. Does anybody have a solution? The codes to both files are under this Text.


Main_Menu.py
import tkinter as tk
from tkinter import PhotoImage

from second_page import SecondPage
from first_page import FirstPage

class Hauptfenster:
def init(self, root):
self.root = root self.root.title("Hauptfenster")

# Bild laden
self.background_image = PhotoImage(file="Background_Main.png")

# Größe des Bildes abrufen
self.width = self.background_image.width()
self.height = self.background_image.height()

# Haupt frame erstellen
self.main_frame = tk.Frame(self.root, width=self.width, height=self.height)
self.main_frame.pack_propagate(False) # Verhindert, dass der Rahmen seine Größe an die Widgets anpasst
self.main_frame.pack() # Packe den Haupt frame, um ihn sichtbar zu machen

# Hintergrundbild hinzufügen
self.background_label = tk.Label(self.main_frame, image=self.background_image)
self.background_label.place(x=0, y=0, relwidth=1, relheight=1) # Füllt das Bild den Rahmen aus

# Rahmen für den ersten Knopf erstellen
self.create_character_frame = tk.Frame(self.main_frame, bg="white", bd=0, relief="flat")
self.create_character_frame.place(relx=0.4, rely=0.7, anchor="center")

# Rahmen für den zweiten Knopf erstellen
self.Archiv_frame = tk.Frame(self.main_frame, bg="white", bd=0, relief="flat")
self.Archiv_frame.place(relx=0.6, rely=0.7, anchor="center")

# Rahmen für den schließen Button
self.close_frame = tk.Frame(self.main_frame, bg="white", bd=0, relief="flat")
self.close_frame.place(relx=0.5, rely=0.9, anchor="center")

# Rahmen für das Logo
self.logo_frame = tk.Frame(self.main_frame, bg="white", bd=0, relief="flat")
self.logo_frame.place(relx=0.5, rely=0.2, anchor="center")

# Text für den ersten Knopf hinzufügen
self.create_character_image = PhotoImage(file="character_text.png")
self.create_character_button = tk.Button(self.create_character_frame, image=self.create_character_image,
relief="flat", command=self.zeige_erste_seite)
self.create_character_button.pack(pady=10)

# Bild für den ersten Knopf hinzufügen

self.first_image = PhotoImage(file="Bild_eins.png")
self.first_image_label = tk.Label(self.main_frame, image=self.first_image, bd=0, highlightthickness=0)
self.first_image_label.place(relx=0.4, rely=0.511, anchor="center")

# Text für den zweiten Knopf hinzufügen
self.Archiv_image = PhotoImage(file="Archiv_Text.png") # Beispielbild, ersetze es mit deinem Bild
self.Archiv_button = tk.Button(self.Archiv_frame, image=self.Archiv_image, relief="flat",
command=self.zeige_zweite_seite)
self.Archiv_button.pack(pady=10)

# Bild für den zweiten Knopf hinzufügen
self.Sheet_image = PhotoImage(file="Bild_zwei.png")
self.Sheet_image_label = tk.Label(self.main_frame, image=self.Sheet_image, bd=0, highlightthickness=0)
self.Sheet_image_label.place(relx=0.6, rely=0.511, anchor="center")

# Button zum Schließen des Programms hinzufügen
self.close_image = PhotoImage(file="Escape.png")
self.close_button = tk.Button(self.close_frame, image=self.close_image, command=root.destroy, relief="flat")
self.close_button.pack(pady=10)

# Logo einfügen
self.logo_image = PhotoImage(file="logo.png")
self.logo_image_label = tk.Label(self.main_frame, image=self.logo_image, bd=0, highlightthickness=0)
self.logo_image_label.place(relx=0.5, rely=0.2, anchor="center")

def zeige_erste_seite(self):
# Alles im Haupt frame löschen
for widget in self.main_frame.winfo_children():
widget.destroy()

# Erstelle ein Objekt der Klasse für die erste Seite
FirstPage(self.main_frame)

def zeige_zweite_seite(self):
# Alles im Haupt frame löschen
for widget in self.main_frame.winfo_children():
widget.destroy()

# Erstelle ein Objekt der Klasse für die zweite Seite
SecondPage(self.main_frame)

def main():
root = tk.Tk()
app = Hauptfenster(root)
root.mainloop()

if name == "main": main()



first_page.py
import tkinter as tk

from Main_Menu import Hauptfenster

class FirstPage(tk.Frame):
def init(self, parent):
self.parent = parent
self.frame = tk.Frame(self.parent)
self.frame.pack(expand=True, fill='both')

# Neuen Inhalt für die zweite Seite hinzufügen
label = tk.Label(self.frame, text="Das ist die erste Seite")
label.pack()

# Button zum Hauptmenü hinzufügen
self.back_to_main_button = tk.Button(self.frame, text="Zurück zum Hauptmenü", command=self.back_to_main)
self.back_to_main_button.pack()

def back_to_main(self):
# Alles im Frame löschen
for widget in self.frame.winfo_children():
widget.destroy()

# Erstelle ein Objekt der Klasse für das Hauptmenü
Hauptfenster(self.parent)



I wanted to switch between those two while they are on separate files.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Write code to match a specific Big-O-Notation

 Programing Coderfunda     March 02, 2024     No comments   

Our class was challenged by a professor at uni that if we were able to find a algorithm that fittingly describes the following Big-O-Notation, we'd instantly pass his class. I wanted to ask if any of you know how this could be done since I've been struggling to make it work without just simplifying it. (Could be any language, i chose c++ for my example)


O(4n · (-2 + 3n) · (n - log(n)) / n) = ?




Simplifying it often gave me either O(n^2) or O(n^3) which would be easy enough to implement but i feel like is not the goal of the challenge.
I've tried directly changing each part into algorithm logic like this:
#include
#include

void Algorithm(int n) {
for (int i = 1; i
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...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • 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...
  • 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...
  • 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...

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