Programming

A place to discuss, learn, and share knowledge about programming. This is a broad community covering all aspects of programming ranging from beginner concepts to advanced topics.

kovacs.bence95

Hello! This code works really well but not able to choose what to display, In order view and in email it displays extra_product_field but i want to display only 'Product'. It have a costum text option in email too but not working, I try everything but it looks like im too beginner for this :( // Display custom field on single product page function d_extra_product_field(){ $value = isset( $_POST['extra_product_field'] ) ? sanitize_text_field( $_POST['extra_product_field'] ) : ''; printf( '<div><label>%s</label><br><textarea name="extra_product_field" value="%s"></textarea></div>', __( 'Enter your custom text' ), esc_attr( $value ) ); } add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 ); // validate when add to cart function d_extra_field_validation($passed, $product_id, $qty){ if( isset( $_POST['extra_product_field'] ) && sanitize_text_field( $_POST['extra_product_field'] ) == '' ){ $product = wc_get_product( $product_id ); wc_add_notice( sprintf( __( '%s cannot be added to the cart until you enter some text.' ), $product->get_title() ), 'error' ); return false; } return $passed; } add_filter( 'woocommerce_add_to_cart_validation', 'd_extra_field_validation', 10, 3 ); // add custom field data in to cart function d_add_cart_item_data( $cart_item, $product_id ){ if( isset( $_POST['extra_product_field'] ) ) { $cart_item['extra_product_field'] = sanitize_text_field( $_POST['extra_product_field'] ); } return $cart_item; } add_filter( 'woocommerce_add_cart_item_data', 'd_add_cart_item_data', 10, 2 ); // load data from session function d_get_cart_data_f_session( $cart_item, $values ) { if ( isset( $values['extra_product_field'] ) ){ $cart_item['extra_product_field'] = $values['extra_product_field']; } return $cart_item; } add_filter( 'woocommerce_get_cart_item_from_session', 'd_get_cart_data_f_session', 20, 2 ); //add meta to order function d_add_order_meta( $item_id, $values ) { if ( ! empty( $values['extra_product_field'] ) ) { woocommerce_add_order_item_meta( $item_id, 'extra_product_field', $values['extra_product_field'] ); } } add_action( 'woocommerce_add_order_item_meta', 'd_add_order_meta', 10, 2 ); // display data in cart function d_get_itemdata( $other_data, $cart_item ) { if ( isset( $cart_item['extra_product_field'] ) ){ $other_data[] = array( 'name' => __( 'Your extra field text' ), 'value' => sanitize_text_field( $cart_item['extra_product_field'] ) ); } return $other_data; } add_filter( 'woocommerce_get_item_data', 'd_get_itemdata', 10, 2 ); // display custom field data in order view function d_dis_metadata_order( $cart_item, $order_item ){ if( isset( $order_item['extra_product_field'] ) ){ $cart_item_meta['extra_product_field'] = $order_item['extra_product_field']; } return $cart_item; } add_filter( 'woocommerce_order_item_product', 'd_dis_metadata_order', 10, 2 ); // add field data in email function d_order_email_data( $fields ) { $fields['extra_product_field'] = __( 'Your extra field text' ); return $fields; } add_filter('woocommerce_email_order_meta_fields', 'd_order_email_data'); // again order function d_order_again_meta_data( $cart_item, $order_item, $order ){ if( isset( $order_item['extra_product_field'] ) ){ $cart_item_meta['extra_product_field'] = $order_item['extra_product_field']; } return $cart_item; } add_filter( 'woocommerce_order_again_cart_item_data', 'd_order_again_meta_data', 10, 3 );

Published 3 months ago
0 likes 93 watched 0 commented
anupamdesign

`my modal form is not working and not redirected to mailbox.my html code<html><body><div id="myModal_pickup" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h2 class="modal-title">Schedule Pickup</h2> </div> <div class="modal-body"> <p id="error_message_pickup"></p> <form id="regiration_form" class="schedule_pickup_form" action="booking_contactform.php"> <fieldset> <div class="form-group"> <input type="text" class="form-control" name="pickname" id="PickName" placeholder="Name"> </div> <div class="form-group"> <textarea class="form-control" name="pickaddress" placeholder="Pickup Address" id="PickAddress"></textarea> </div> <div class="form-group"> <input type="tel" class="form-control" id="PickNumber" name="picknumber" placeholder="Contact Number" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"> </div> <div class="form-group"> <input type="email" class="form-control" id="PickEmail" name="pickemail" placeholder="Email"> </div> <input type="button" name="next" class="next btn pickup_btn" value="Next"> </fieldset> <fieldset> <div class="form-group"> <input type="date" class="form-control" name="pickdate" id="PickDate" placeholder=""> </div> <div class="form-group"> <label for="lName">Time Slot</label><br> <input type="radio" name="picktimeslot" id="pick1" value="10:00am - 1:00 pm" checked> 10:00am - 1:00 pm <input type="radio" name="picktimeslot" id="pick2" value="1:00pm - 4:00pm"> 1:00pm - 4:00pm <input type="radio" name="picktimeslot" id="pick3" value="4:00pm - 7:00pm"> 4:00pm - 7:00pm </div> <input type="button" name="previous" class="previous btn btn-default " value="Previous"> <input type="submit" name="submit_book" class="submit btn pickup_btn" value="Submit" onclick="validateSchedulePickup()" id="submit_data"> </fieldset> </form></body></html>my modal css<style>#myModal_pickup .modal-body{ text-align:left; padding:10px 30px 40px 30px; } .previous{ background-color: transparent; border: 2px solid #c5a759; color: #c5a759; font-size:14px; font-family: 'd-din_expregular'; border-radius:0px; padding:4px 15px; transition: all 0.3s ease-in-out; } .previous:hover{ background-color:#c5a759; border:2px solid #c5a759; color:#fff; } .previous:focus{ outline:none; } .pickup_btn{ transition: all 0.3s ease-in-out; background-color:#c5a759; border:2px solid #c5a759; color:#fff; font-size:14px; border-radius:0px; padding:4px 15px; font-family: 'd-din_expregular'; } .pickup_btn:hover{ background-color: transparent; border: 2px solid #c5a759; color: #c5a759; } .pickup_btn:focus{ outline:none; } .error{color: #f00;}</style>my javascript<script> function validateSchedulePickup() { event.preventDefault(); var pickname = $("#PickName").val(); var pickaddress = $("#PickAddress").val(); var pickemail = $("#PickEmail").val(); var pickdate = $("#PickDate").val(); var picknumber = $("#PickNumber").val(); var picktimeslot = $("input[name='picktimeslot']:checked").val(); $(".error").remove(); if (pickname.length < 2) { $('#PickName').after('<span class="error">Name is required</span>'); } if (pickaddress.length < 10) { $('#PickAddress').after('<span class="error">Address is required</span>'); } if (pickdate.length < 1) { $('#PickDate').after('<span class="error">Date is required</span>'); } if (picknumber.length < 1) { $('#PickNumber').after('<span class="error">Phone number is required</span>'); } else { var regNu = /([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/; var validNumber = regNu.test(picknumber); if (!validNumber) { $('#PickNumber').after('<span class="error">Enter a valid Number</span>'); } } if (pickemail.length < 1) { $('#Pickemail').after('<span class="error">Email is required</span>'); } else { var regEx = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i; var validEmail = regEx.test(pickemail); if (!validEmail) { $('#Pickemail').after('<span class="error">Enter a valid email</span>'); } } if(pickname == '' || pickaddress == '' || pickemail == '' || picknumber == '' || pickdate == '' || picktimeslot == '') { $('#error_message_pickup').html("<span class='error'>All Detail is required</span>"); } else { $.ajax({ url:"booking_contactform.php", method:"POST", data:{pickname:pickname, pickaddress:pickaddress, picknumber:picknumber, pickemail:pickemail, pickdate:pickdate, picktimeslot:picktimeslot}, success:function(data){ $('#error_message_pickup').html("Thank you! for pickup request"); $("form").trigger("reset"); } }); event.preventDefault(); } return false;</script>here is my php code<?php if(isset($_POST['submit_book'])){`your text` $to = "[email protected]"; // this is your Email address $from = $_POST['email']; // this is the sender's Email address $pickname = $_POST['pickname']; $pickaddress = $_POST['pickaddress']; $picknumber = $_POST['picknumber']; $pickemail = $_POST['pickemail']; $pickdate = $_POST['pickdate']; $picktimeslot = $_POST['picktimeslot']; $book_subject = "Booking submission"; // $message = " Name : ".$name."\n\n"." Email : ".$email."\n\n"." Phone : ".$phone."\n\n"." Message : ".$contet." wrote the following: "."\n\n".$_POST['message'];$message = $pickname."\n\n".$pickaddress."\n\n".$picknumber."\n\n".$pickemail."\n\n".$pickdate."\n\n".$picktimeslot."\n\n". $_POST['message']; $headers = "From:" . $from; mail($to,$book_subject,$message,$headers); header('Location: index.php'); }?>

Published 3 months ago
1 likes 91 watched 0 commented
samerike123

import pygameimport randomfrom pygame.locals import *import timepygame.init()# Screen dimensionsscreen_width = 800screen_height = 600# Initialize pygame screenscreen = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption('Simple Game')# Game variables for the first gameplayer_width = 50player_height = 50player_pos2 = [screen_width - 100, 270]player_pos1 = [screen_width - 100, 430]player_speed = 5enemy1_width = 50enemy1_height = 50enemy1_speed = 3enemies1 = []score1 = 0game_over1 = Falsewin1 = Falsegame_active = True# Game variables for the second gameplayer2_width = 50normal_height = 50crouch_height = 25player_pos = [0, screen_height - normal_height]player_speed = 5player_current_height = normal_heightenemy2_width = 40enemy2_height = 25initial_enemy2_speed = 3enemy2_speed = initial_enemy2_speedenemies2 = []score2 = 0game_over2 = Falsewin2 = Falsestart_ticks = pygame.time.get_ticks()boom = 1000start2_ticks = pygame.time.get_ticks()# Function to spawn enemy for the first gamedef spawn_enemy_game1():x = 0y = random.randint(60, screen_height - 110)enemies1.append(pygame.Rect(x, y, enemy1_width, enemy1_height))# Function to spawn enemy for the second gamedef spawn_enemy_game2():y = random.choice([screen_height - 50, screen_height - 25])enemy = pygame.Rect(screen_width, y, enemy2_width, enemy2_height)enemies2.append(enemy)# Function to check collision with player in the first gamedef check_collision_game1(player_rect1, player_rect2):for enemy in enemies1:if player_rect1.colliderect(enemy) or player_rect2.colliderect(enemy):return Truereturn False# Function to check collision with player in the second gamedef check_collision_game2(player_rect):for enemy in enemies2:if player_rect.colliderect(enemy):return Truereturn False# Function to restart game for the first gamedef restart_game1():global player_pos1, player_pos2, enemies1, game_over1, win1, score1player_pos1 = [screen_width - 100, 430]player_pos2 = [screen_width - 100, 270]enemies1.clear()game_over1 = Falsewin1 = Falsescore1 = 0# Function to restart game for the second gamedef restart_game2():global player_pos, enemies2, game_over2, win2, enemy2_speed, start_ticks, player_current_height, score2, player2_width, boom, start2_ticksplayer_current_height = normal_heightplayer_pos = [0, screen_height - normal_height]enemies2.clear()game_over2 = Falsewin2 = Falseenemy2_speed = initial_enemy2_speedstart_ticks = pygame.time.get_ticks()start2_ticks = pygame.time.get_ticks()score2 = 0player2_width = 50boom = 1000# Menu functiondef show_menu():screen.fill((0, 0, 0))menu_font = pygame.font.SysFont(None, 60)menu_text1 = menu_font.render('Press 1 to open first game', True, (255, 255, 255))menu_text2 = menu_font.render('Press 2 to open the other game', True, (255, 255, 255))screen.blit(menu_text1, (screen_width // 2 - menu_text1.get_width() // 2, screen_height // 2 - 30))screen.blit(menu_text2, (screen_width // 2 - menu_text2.get_width() // 2, screen_height // 2 + 30))pygame.display.flip()# Function to show pause menudef show_pause_menu():screen.fill((0, 0, 0))pause_font = pygame.font.SysFont(None, 60)pause_text = pause_font.render('Press SPACE to Continue', True, (255, 255, 255))screen.blit(pause_text, (screen_width // 2 - pause_text.get_width() // 2, screen_height // 2 - 30))pygame.display.flip()# Function to show game over menudef show_game_over_menu():screen.fill((0, 0, 0))game_over_font = pygame.font.SysFont(None, 60)game_over_text = game_over_font.render("Game Over!", True, (255, 0, 0))screen.blit(game_over_text, (screen_width // 2 - game_over_text.get_width() // 2, screen_height // 2 - 30))pygame.display.flip()# Function to show win menudef show_win_menu():global game_activescreen.fill((0, 0, 0))win_font = pygame.font.SysFont(None, 60)win_text = win_font.render("You Win!", True, (0, 255, 0))screen.blit(win_text, (screen_width // 2 - win_text.get_width() // 2, screen_height // 2 - 30))pygame.display.flip()game_active = False# Game loopclock = pygame.time.Clock()running = Truein_menu = Truegame1_active = Falsegame2_active = Falsepaused = Falseshow_pause = Falsewhile running:dt = clock.tick(60) / 1000.0for event in pygame.event.get():if event.type == QUIT:running = Falseif event.type == pygame.KEYDOWN:if win2:if event.key == pygame.K_r:paused = Falsewin2 = False # Reset win2 to avoid re-entering this block immediatelyrestart_game2()elif event.type == KEYDOWN:if event.key == K_ESCAPE:if not in_menu:if not paused:paused = Trueshow_pause = Trueelse:paused = Falseshow_pause = Falseelif event.key == K_SPACE and show_pause:paused = Falseshow_pause = Falseelif event.key == K_m:if not in_menu:in_menu = Truegame1_active = Falsegame2_active = Falseelif event.key == K_1:if in_menu:in_menu = Falsegame1_active = Truegame2_active = Falserestart_game1()elif event.key == K_2:if in_menu:in_menu = Falsegame1_active = Falsegame2_active = Truerestart_game2()elif event.key == K_r:if game1_active and game_over1:restart_game1()if game2_active and game_over2:restart_game2()elif event.key == K_DOWN:if game2_active:player_current_height = crouch_heightplayer_pos[1] = screen_height - crouch_heightelif event.key == K_UP:if game2_active:player_current_height = crouch_heightplayer_pos[1] = 550current_time = pygame.time.get_ticks()# Calculate the elapsed timeelapsed_time = (current_time - start2_ticks) / 1000 # Convert milliseconds to seconds# Adjust boom and player width based on elapsed timeif 10 <= score2 < 20:boom = 500player2_width = 25if 20 <= score2 < 30:boom = 400player2_width = 12.5if 30 <= elapsed_time <= 40:boom = 300if 40 <= score2:boom = 250if in_menu:show_menu()elif show_pause:show_pause_menu()elif game1_active:if not paused:keys = pygame.key.get_pressed()if keys[K_DOWN] and player_pos2[1] + player_height < screen_height:player_pos2[1] += player_speedplayer_pos1[1] += player_speedif keys[K_UP] and player_pos2[1] > 0:player_pos2[1] -= player_speedplayer_pos1[1] -= player_speedplayer_pos1[1] = max(0, min(player_pos1[1], screen_height - player_height))player_pos2[1] = max(0, min(player_pos2[1], 390))player_rect1 = pygame.Rect(player_pos1[0], player_pos1[1], player_width, player_height)player_rect2 = pygame.Rect(player_pos2[0], player_pos2[1], player_width, player_height)middle_top = min(player_pos1[1], player_pos2[1]) + player_heightmiddle_bottom = max(player_pos1[1], player_pos2[1])middle_rect = pygame.Rect(player_pos1[0], middle_top, 60, middle_bottom - middle_top)if random.randint(1, 100) == 1:spawn_enemy_game1()for enemy in enemies1[:]:enemy.x += enemy1_speedif enemy.x > screen_width:enemies1.remove(enemy)if check_collision_game1(player_rect1, player_rect2):game_over1 = Truescreen.fill((0, 0, 0))pygame.draw.rect(screen, (255, 255, 255), player_rect1)pygame.draw.rect(screen, (255, 255, 255), player_rect2)for enemy in enemies1[:]:pygame.draw.rect(screen, (255, 0, 0), enemy)if enemy.colliderect(middle_rect):score1 += 1enemies1.remove(enemy)score_font = pygame.font.SysFont(None, 36)score_text = score_font.render(f"Score: {score1}", True, (255, 255, 255))screen.blit(score_text, (10, 10))if game_over1:show_game_over_menu()elif game2_active:if not paused:keys = pygame.key.get_pressed()if keys[K_UP]:player_current_height = crouch_heightplayer_pos[1] = 550elif keys[K_DOWN]:player_current_height = crouch_heightplayer_pos[1] = screen_height - crouch_heightelse:player_current_height = 50player_pos[1] = 550if pygame.time.get_ticks() - start_ticks > boom:spawn_enemy_game2()start_ticks = pygame.time.get_ticks()for enemy in enemies2[:]:enemy.x -= enemy2_speedif enemy.x < 0:score2 += 1enemies2.remove(enemy)if score2 >= 1:win2 = Trueif check_collision_game2(pygame.Rect(player_pos[0], player_pos[1], player2_width, player_current_height)):game_over2 = Truescreen.fill((0, 0, 0))pygame.draw.rect(screen, (255, 255, 255),pygame.Rect(player_pos[0], player_pos[1], player2_width, player_current_height))for enemy in enemies2[:]:pygame.draw.rect(screen, (255, 0, 0), enemy)score_font = pygame.font.SysFont(None, 36)score_text = score_font.render(f"Score: {score2}", True, (255, 255, 255))screen.blit(score_text, (10, 10))if game_over2:show_game_over_menu()pygame.display.flip()pygame.quit()can anyone help me fix the win2 function it shuld be like this Show up a win screen and restart the game if r pressed and open menu if m pressed

Published 4 months ago
1 likes 98 watched 0 commented
codie
codie

I was working in Phoenix/Elixir and created a function component for navbar, and got this issue:Done in 38ms. Compiling 1 file (.ex) error: undefined function sigil_p/2 (expected RankgistWeb.NavComponents to define such a function or for it to be imported, but none are available) │ 55 │ href={~p"/users/log_out"} │ ^^^^^^^^^^^^^^^^^^^^^^^^^ │ └─ (rankgist 0.1.0) lib/rankgist_web/components/nav_components.ex:55: RankgistWeb.NavComponents.main/1 error: undefined function sigil_p/2 (expected RankgistWeb.NavComponents to define such a function or for it to be imported, but none are available) │ 45 │ href={~p"/track-competitors"} │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ │ └─ (rankgist 0.1.0) lib/rankgist_web/components/nav_components.ex:45: RankgistWeb.NavComponents.main/1 error: undefined function sigil_p/2 (expected RankgistWeb.NavComponents to define such a function or for it to be imported, but none are available) │ 8 │ <.link href={~p"/"} class="flex items-center space-x-3 rtl:space-x-reverse"> │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ │ └─ (rankgist 0.1.0) lib/rankgist_web/components/nav_components.ex:8: RankgistWeb.NavComponents.main/1 == Compilation error in file lib/rankgist_web/components/nav_components.ex == ** (CompileError) lib/rankgist_web/components/nav_components.ex: cannot compile module RankgistWeb.NavComponents (errors have been logged) Compiling 1 file (.ex) error: undefined function sigil_p/2 (expected RankgistWeb.NavComponents to define such a function or for it to be imported, but none are available) │ 55 │ href={~p"/users/log_out"} │ ^^^^^^^^^^^^^^^^^^^^^^^^^ │ └─ (rankgist 0.1.0) lib/rankgist_web/components/nav_components.ex:55: RankgistWeb.NavComponents.main/1 error: undefined function sigil_p/2 (expected RankgistWeb.NavComponents to define such a function or for it to be imported, but none are available) │ 45 │ href={~p"/track-competitors"} │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ │ └─ (rankgist 0.1.0) lib/rankgist_web/components/nav_components.ex:45: RankgistWeb.NavComponents.main/1 error: undefined function sigil_p/2 (expected RankgistWeb.NavComponents to define such a function or for it to be imported, but none are available) │ 8 │ <.link href={~p"/"} class="flex items-center space-x-3 rtl:space-x-reverse"> │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ │ └─ (rankgist 0.1.0) lib/rankgist_web/components/nav_components.ex:8: RankgistWeb.NavComponents.main/1 == Compilation error in file lib/rankgist_web/components/nav_components.ex == ** (CompileError) lib/rankgist_web/components/nav_components.ex: cannot compile module RankgistWeb.NavComponents (errors have been logged)to fix the issue of sigil_p/2 being undefined:defmodule LiveViewAppWeb.NavComponents do use Phoenix.Component use LiveViewAppWeb, :verified_routes def main(assigns) do ~H"""...use LiveViewAppWeb, :verified_routes adding this fixed it.

Published 4 months ago
1 likes 161 watched 0 commented
codie
codie

I've been trying sudo apt-get update in Ubuntu 20.04 LTS server, and I was getting the below error.W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal/InRelease Temporary failure resolving 'archive.ubuntu.com' W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal-updates/InRelease Temporary failure resolving 'archive.ubuntu.com' W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/focal-backports/InRelease Temporary failure resolving 'archive.ubuntu.com' W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/focal-security/InRelease Temporary failure resolving 'security.ubuntu.com' W: Failed to fetch http://ppa.launchpad.net/certbot/certbot/ubuntu/dists/focal/InRelease Temporary failure resolving 'ppa.launchpad.net' W: Failed to fetch http://rpms.litespeedtech.com/debian/dists/focal/InRelease Temporary failure resolving 'rpms.litespeedtech.com' W: Some index files failed to download. They have been ignored, or old ones used instead.Fix for Temporary failure resolving us.archive.ubuntu.comHere's how I fixed it:Removing bad sources.listsudo rm -rf /etc/apt/sources.list*Adding new good sources.listcd /etc/apt/ wget https://gist.githubusercontent.com/ishad0w/788555191c7037e249a439542c53e170/raw/3822ba49241e6fd851ca1c1cbcc4d7e87382f484/sources.listFixing the Ubuntu's connectionsudo dhclient -v -4 sudo echo 'nameserver 8.8.8.8' > /etc/resolv.confRunning the update commandsudo apt-get updateHooray! you fixed it.

Published 4 months ago
1 likes 180 watched 0 commented
codie
codie

Hey Devs.I started learning Django in COVID times. I was on my grade 12th ATM. I was into content writing and stuff. I had a site, and there was a tool named "Adsense Eligibility Checker" in my site, where user could fill the form, submit their site, and I'd check if there site is eligible or not. The requests were a lot, and task was tedious.I wanted to build something where my presence would not be required. So, I started searching for ways to make a tool/webapp. I was already into learning Python, so maybe fate wanted or something, I got to know about Django.I started learning it. It took me three weeks to nicely learn and 2-3 weeks to develop that tool. I was super happy, wanted to deploy on my cpanel-shared-hosting based server, I had to suffer a lot at that time. But does tons of searches, I deployed it. It got popular, I attached Google Ads on that platform, made a little good money, travelled to places in Nepal.My father's friend used to do Fiverr in Poland, and she suggested me to do so. I had some old Fiverr gigs added, but removed them (were primarily for Photoshop editing). Add a gig, "I'll deploy Django on cPanel", after 2 days of adding that gig, got an order from a Morroco-ian guy. Delivered it. And my journey boosted.I kept doing indie dev and freelancing. After 2 years, my revenue were not doing so well. Had to apply for a job, got the job, worked there for 5 and a half months, and US-based company named "Blogstorm.AI" offered me a job with comparatively good salary, started working there. It's been 1 and a half years working on blogstorm.Now, I am doing full-time job, indie dev and open source. There's a Django rest API framework, that I am working, called Djapy.IO . The journey is going good. I have migrated all my platforms code to Djapy.I hope to see some new guys in there. Life is good man, so is Django. Have a great day. For suggestions, believe on process.

Zaeemusmani replied 8 months ago
Noce good lovly
Published 8 months ago
4 likes 1734 watched 3 commented
codie
codie

Django Recaptcha v3 will be installed in your Django website soon, just follow my instructions. We will be using Google Recaptcha version 3 ( I am not a robot ) and a Python library django-recaptcha for this task.This is a repost of an old blog of ours.How to install, deploy or integrate Django recaptcha v3?Django recaptcha v3 installationFirst, install django-recaptcha in your virtual workspace.Visit the GitHub Repo of this task/project to get all the source codes.Install and configure django-recaptcha libpip install django-recaptchaNow, add captcha in the INSTALLED_APPS section in your settings.pycaptchaMust be similar to this:INSTALLED_APPS = [ 'captcha', # add this code 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "your_app_name", # app name ]Recaptcha keys configurationAdd RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY at the last lines of your settings.pyRECAPTCHA_PUBLIC_KEY = 'MyRecaptchaKey123' RECAPTCHA_PRIVATE_KEY = 'MyRecaptchaPrivateKey456'Here, RECAPTCHA_PUBLIC_KEY means SITE KEY and RECAPTCHA_PRIVATE_KEY means SECRET KEY.Now, go to Google reCAPTCHA admin panel and register your site for reCAPTCHA and use those data in the upper code.Cpatcha Form configurationNow, create a file named my_captcha.py and inside it you need to write the following Python codes:from django import forms from captcha.fields import ReCaptchaField class FormWithCaptcha(forms.Form): captcha = ReCaptchaField()Django views configurationWrite a context with "captcha" variable name that with render the form we have coded in FormWithCaptcha which is inside the my_captcha.py .from django.shortcuts import render from .my_captcha import FormWithCaptcha # Create your views here. def home(request): context = { "captcha": FormWithCaptcha, } return render(request, "home.html", context)Rendering recaptcha v3Now, we are rendering recaptcha using the Jinja template method. Use {{captcha}} for rendering the captcha form.For now, have a look here:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <forms> {{captcha}} </forms> </body> </html>Getting data from recaptcha formTo get data from django recaptcha, you need to use g-recaptcha-response.get_recaptcha = request.POST.get("g-recaptcha-response")This will return true if the checkbox is checked, else false.

codie replied 8 months ago
You might also wanna check this video:https://youtu.be/8GNc4Pz4is4
Published 8 months ago
1 likes 747 watched 1 commented
codie
codie

[REPOST] I am a noob at Python in Windows. I am getting env\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. The issue in my Windows machine while activating the virtual environment. Can somebody help me, I am on my Visual Studio CODE.PS C:\Users\USER\Projects\content_idea_gen> env/Scripts/activate env/Scripts/activate : File C:\Users\USER\Projects\content_idea_gen\env\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + env/Scripts/activate + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess

khanzain4593 replied 5 months ago
You need to change the PowerShell execution policy to allow scripts to run. Here's how to do it:1. Open PowerShell as Administrator: - Press Win + X and select "Windows PowerShell (Admin)".2. Set the Execution Policy: - Run this command to allow local scripts to run: ```powershell Set-ExecutionPolicy RemoteSigned ```3. Confirm the Change: - Type Y and press Enter to confirm.4. Activate the Virtual Environment: - Close and reopen PowerShell or your VS Code terminal. - Activate your virtual environment with: ```powershell .\env\Scripts\Activate.ps1 ```This should resolve the issue and allow you to activate your virtual environment.For better understanding, here are the some excellent learning platforms.1. W3 School 2. Iqra Technology 3. JavatPoint
Published 8 months ago
0 likes 983 watched 2 commented
codie
codie

Deploying SvelteKit can be a tricky job, especially when you're doing it for the first time, unlike me. But, after a few deployments, you get used to with it. So, today, I am guiding you through it, and giving you exact ways to deploy and run your SvelteKit in the server.Also, will be talking about something that I personally developed, called svelte-deploy command.SvelteKit configurationFirst of all, you need a module to be installed in your sveltekit project, @sveltejs/adapter-node;npm install @sveltejs/adapter-nodeNow, you have to configure your svelte.config.js, by adding replacing that upper module with @sveltejs/adapter-auto;import adapter from '@sveltejs/adapter-node'; // ^ // replace @sveltejs/adapter-auto | const config = { preprocess: [ vitePreprocess(), preprocess({ postcss: true }) ], ...Now, your SvelteKit setup is almost done.Server setupIf you have installed git in your Lightsail server then what you have to do is, clone your repo to a specific folder.Creating a service setupNow, we need to create a service setup /etc/systemd/system/<your_svelte_service_name>.service:[Unit] Description=SvelteApp After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/svelte-apps/<path-to-your-app> ExecStart=/home/ubuntu/.nvm/versions/node/v19.8.0/bin/node /home/ubuntu/svelte-apps/<path-to-your-app>/build/index.js Environment=PORT=3099 ORIGIN=https://yoursite.com [Install] WantedBy=multi-user.targetMake sure you have installed NodeJs, suggested to installed it using nvm. You can see learn about installing nvm here.And to checkout the path of your current running node, use whereis node, and paste your preferred node to ExecStart=path_to_node path_to_index.jsNginx Setupupstream sveltekit-frontend { server localhost:3099; } server { listen 80; listen [::]:80; set $app_dir "/home/ubuntu/svelte-apps/<path-to-your-app>"; # not required server_name yoursite.com; location / { proxy_pass http://sveltekit-frontend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }Now, run;sudo nginx -tIf result is:nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successfulIt's usually good, and you're ready to go. (if not, ask below, happy to help)Restart the servicesNow, restart the nginx and the created services:sudo systemctl enable <your_svelte_service_name>.service; sudo systemctl start <your_svelte_service_name>.service; sudo systemctl restart nginx.service;Done, now your site is up and running. Lemme know if you need help.Have a good day 😊

Published 8 months ago
3 likes 999 watched 0 commented
aryangupta001

Q2: Let A[n] be an array of n distinct integers. If i < j and A[i] > A[j], then the pair (i, j)is called an inversion of A. Write a C/C++ program that determines the number ofinversions in any permutation on n elements in O(n lg n) worst-case time.(Hint: Modify merge sort)Example: A = {4, 1, 3, 2} output is 4program:-#include<stdio.h> int total_inversions(int arr[], int n, int count); int main(){ int arr[] = {4, 1, 3, 2}; int n = sizeof(arr) / sizeof(arr[0]); int count = 0; count = total_inversions(arr, n , count); printf("%d", count); return 0; } int total_inversions(int arr[], int n, int count){ for(int i = 0; i < n-1; i++){ for(int j = i+1; j < n; j++){ if (arr[i] > arr[j]){ count++; } } } return count; }

somesh replied 9 months ago
Hey buddy!As you well know, the program you've suggested here is great, reliable but there's a certain hitch. It runs with a time complexity of O(n^2). This might not seem like a big deal but when you're dealing with huge arrays with a large number of elements, it may cause performance issues. The challenge here is finding the number of inversions in a permutation on n elements, but the trick is doing it within O(nlogn) worst-case time. A smart modification of the merge sort algorithm can be a real game changer here, and lucky for you, I tweaked it to our benefit here: #include<stdio.h> int merge(int arr[], int temp[], int left, int mid, int right); int _mergeSort(int arr[], int temp[], int left, int right); int inversionCount(int arr[], int n) { int temp[n]; return _mergeSort(arr, temp, 0, n - 1); } int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { mid = (right + left)/2; inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); inv_count += merge(arr, temp, left, mid+1, right); } return inv_count; } int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int inv_count = 0; i = left; j = mid; k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } while (i <= mid - 1) temp[k++] = arr[i++]; while (j <= right) temp[k++] = arr[j++]; for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count; } int main(int argv, char **args) { int arr[] = {4, 1, 3, 2}; printf("Number of inversions are %d \n", inversionCount(arr, sizeof(arr)/sizeof(arr[0]))); return 0; } As you asked, this piece of code will help you get the inversion count in an array and that too in O(nlogn) time complexity, thanks to merge sort.And before I close the lid on this one, I hope you are doing alright handling the pointers and recursion here. The inversion counting part is the only trick in this pudding. Remember, for every i in the first array, if j is an element in the second array, all elements after i in the first subarray and j in the second subarray will form valid inversions. So simply add up (mid – i) inversions for all such valid i and j!This should help you out. Let me know if you need me to break it down more.Happy Coding!
Published 9 months ago
0 likes 567 watched 1 commented
tej
tej

I tried to create a simple embed HTTP server in Rust using Actix Web for the Desktop Tauri app. However, I found a lot of problems and unable to perform a simple file upload operation and have Websocket without extra dependencies. None of the stackoverflow solution worked for me.May be I am a Django Guy and found difficult to use Actix Web which may be my skill issue. So I thought to create my own web framework in Rust for embed projects.Here's github link: https://github.com/tejmagar/rusty-web/It is same like a Django's functional approach.use rusty_web::paths::{Path, Paths}; use rusty_web::request::Request; use rusty_web::response::Response; use rusty_web::server::run_server; fn home(request: Request, mut response: Response) { response.html(200, "Home Page".to_string()).send(); } fn about(request: Request, mut response: Response) { response.html(200, "About Us".to_string()).send(); } fn main() { let paths: Paths = vec![ Path::new("/".to_string(), home), Path::new("/about/".to_string(), about), ]; run_server("0.0.0.0:8080", paths); }I will be using this for my personal projects. Leave your suggestions to make this project better.

codie replied 9 months ago
Use struct.struct XYZStruct { var_1: String var_2: String var_3: AnotherStruct } struct AnotherStruct {}and something like this:fn about(request: Request, mut response: Response) { response.json(Status::Ok, XYZStruct::new(...)).send(); }
Published 9 months ago
1 likes 1163 watched 4 commented