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

02 December, 2023

hi..i am creating a personal book management system. i want to delete book information(ISBN, author name,title) from the database

 Programing Coderfunda     December 02, 2023     No comments   

my code doesnt work. i dont know why..it should delete the isbn from the database
def delbook_by_isbn(database):
search_information = input("Enter ISBN to delete the book: ")
book_matched = search_books_by_information(database, search_information)
if not book_matched:
print("No matching records found.")
return database

print("\nMatching Books:")
for row in book_matched:
print(row)

delete_option = input("Do you want to delete information of this book? (yes/no): ").lower()

if delete_option == 'yes':
for book in book_matched:
database.remove(book)
print("Books deleted successfully.")
return database
else:
print("No books deleted.")
return database
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

RAG as part of flow

 Programing Coderfunda     December 02, 2023     No comments   

I was wondering if someone has experience with real-life RAG flows.


A very simple scenario


User asks: Give me the top 5 takeaways "search phrase" (e.g. MS keynote)


The code behind it runs an Azure AI search and returns five relevant documents - that are passed via a prompt including the user's original question to the AI


The system answers with a text with the top 5 takeaways


And this is where most of examples on the internet end


How do you handle the following question from user:


Give me 5 more takeaways


If you ran azure search with this phrase, you will not for sure get anything relevant to the original question, or do you pass this question straight to AI where you include chat history, original question, original RAG and AI answer?


What are your experiences?


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

Computing gradient of output with respect to an intermediate layer in Theano

 Programing Coderfunda     December 02, 2023     No comments   

I'm trying to implement heatmaps of class activation in theano, based on section 5.4.3 Visualizing heatmaps of class activation of Deep learning with Python.


I'm able to compute the gradient of the predicted class (class 0) with regard to input samples in the mini-batch. Here are the relevant parts of my code:
import theano.tensor as T
import numpy as np
import lasagne as nn
import importlib
import theano
from global_vars import *
theano.config.floatX = 'float32'

seq_len = 19
num_features = 42
config_name = 'pureConv'
config_initialize(config_name)

metadata_path = "metadata/pureConv/dump_pureConv-20230429-160908-223.pkl"
metadata = np.load(metadata_path, allow_pickle=True)

config = importlib.import_module("configurations.%s" % config_name)
params = np.array(metadata['param_values'])
l_in, l_out = config.build_model()
nn.layers.set_all_param_values(l_out, metadata['param_values'])

all_layers = nn.layers.get_all_layers(l_out)
i=0
for layer in all_layers:
#name = string.ljust(layer.__class__.__name__, 32)
name = layer.__class__.__name__
print(" layer %d: %s %s %s" % (i, name, nn.layers.get_output_shape(layer), nn.layers.count_params(layer)))
i+=1

layer_name = all_layers[34]
sym_x = T.tensor3()
conv_output = nn.layers.get_output(layer_name, sym_x, deterministic=True) #Conv1DLayer
nn_output = nn.layers.get_output(l_out, sym_x, deterministic=True) #softmax output
grads = theano.gradient.jacobian(nn_output[:,0], wrt=sym_x)
res = theano.function(inputs=[sym_x], outputs=[nn_output, conv_output, grads],allow_input_downcast=True)
input_data = np.random.random((64, seq_len, num_features))

out, conv, grads =res(input_data)
print("Model output shape", out.shape)
print("Conv output shape",conv.shape)
print("Gradients out shape", grads.shape)



, which output:
layer 0: InputLayer (None, 19, 42) 0
layer 1: DimshuffleLayer (None, 42, 19) 0
layer 2: Conv1DLayer (None, 16, 19) 2016
layer 3: BatchNormLayer (None, 16, 19) 2080
layer 4: NonlinearityLayer (None, 16, 19) 2080
layer 5: Conv1DLayer (None, 16, 19) 3360
layer 6: BatchNormLayer (None, 16, 19) 3424
layer 7: NonlinearityLayer (None, 16, 19) 3424
layer 8: Conv1DLayer (None, 16, 19) 4704
layer 9: BatchNormLayer (None, 16, 19) 4768
layer 10: NonlinearityLayer (None, 16, 19) 4768
layer 11: ConcatLayer (None, 48, 19) 10272
layer 12: DimshuffleLayer (None, 19, 48) 10272
layer 13: ConcatLayer (None, 19, 90) 10272
layer 14: DimshuffleLayer (None, 90, 19) 10272
layer 15: Conv1DLayer (None, 16, 19) 14592
layer 16: BatchNormLayer (None, 16, 19) 14656
layer 17: NonlinearityLayer (None, 16, 19) 14656
layer 18: Conv1DLayer (None, 16, 19) 17472
layer 19: BatchNormLayer (None, 16, 19) 17536
layer 20: NonlinearityLayer (None, 16, 19) 17536
layer 21: Conv1DLayer (None, 16, 19) 20352
layer 22: BatchNormLayer (None, 16, 19) 20416
layer 23: NonlinearityLayer (None, 16, 19) 20416
layer 24: ConcatLayer (None, 48, 19) 32064
layer 25: DimshuffleLayer (None, 19, 48) 32064
layer 26: ConcatLayer (None, 19, 138) 32064
layer 27: DimshuffleLayer (None, 138, 19) 32064
layer 28: Conv1DLayer (None, 16, 19) 38688
layer 29: BatchNormLayer (None, 16, 19) 38752
layer 30: NonlinearityLayer (None, 16, 19) 38752
layer 31: Conv1DLayer (None, 16, 19) 43104
layer 32: BatchNormLayer (None, 16, 19) 43168
layer 33: NonlinearityLayer (None, 16, 19) 43168
layer 34: Conv1DLayer (None, 16, 19) 47520
layer 35: BatchNormLayer (None, 16, 19) 47584
layer 36: NonlinearityLayer (None, 16, 19) 47584
layer 37: ConcatLayer (None, 48, 19) 65376
layer 38: DimshuffleLayer (None, 19, 48) 65376
layer 39: ConcatLayer (None, 19, 186) 65376
layer 40: ReshapeLayer (64, 3534) 65376
layer 41: DenseLayer (64, 200) 772176
layer 42: BatchNormLayer (64, 200) 772976
layer 43: NonlinearityLayer (64, 200) 772976
layer 44: DenseLayer (64, 8) 774584
layer 45: NonlinearityLayer (64, 8) 774584

Model output shape (64, 8)
Conv output shape (64, 16, 19)
Gradients out shape (64, 64, 19, 42)



However, I've been having a lot of trouble figuring out how compute the gradient of the predicted class with regard to the output feature map of selected intermediate convolutional layer. as when I try the following line:
grads = theano.gradient.jacobian(nn_output[:,0], wrt=conv_output)



output the following error:
---------------------------------------------------------------------------
DisconnectedInputError Traceback (most recent call last)
Cell In[46], line 36
34 conv_output = nn.layers.get_output(layer_name, sym_x, deterministic=True) #Conv1DLayer
35 nn_output = nn.layers.get_output(l_out, sym_x, deterministic=True) #softmax output
---> 36 grads = theano.gradient.jacobian(nn_output[:,0], conv_output)
37 res = theano.function(inputs=[sym_x], outputs=[nn_output, conv_output, grads],allow_input_downcast=True)
38 input_data = np.random.random((64, seq_len, num_features))

File *\lib\site-packages\theano\gradient.py:1912, in jacobian(expression, wrt, consider_constant, disconnected_inputs)
1907 return rvals
1908 # Computing the gradients does not affect the random seeds on any random
1909 # generator used n expression (because during computing gradients we are
1910 # just backtracking over old values. (rp Jan 2012 - if anyone has a
1911 # counter example please show me)
-> 1912 jacobs, updates = theano.scan(inner_function,
1913 sequences=arange(expression.shape[0]),
1914 non_sequences=[expression] + wrt)
1915 assert not updates, \
1916 ("Scan has returned a list of updates. This should not "
1917 "happen! Report this to theano-users (also include the "
1918 "script that generated the error)")
1919 return format_as(using_list, using_tuple, jacobs)

File *\lib\site-packages\theano\scan_module\scan.py:774, in scan(fn, sequences, outputs_info, non_sequences, n_steps, truncate_gradient, go_backwards, mode, name, profile, allow_gc, strict, return_list)
768 dummy_args = [arg for arg in args
769 if (not isinstance(arg, SharedVariable) and
770 not isinstance(arg, tensor.Constant))]
771 # when we apply the lambda expression we get a mixture of update rules
772 # and outputs that needs to be separated
--> 774 condition, outputs, updates = scan_utils.get_updates_and_outputs(fn(*args))
775 if condition is not None:
776 as_while = True

File *\lib\site-packages\theano\gradient.py:1902, in jacobian..inner_function(*args)
1900 rvals = []
1901 for inp in args[2:]:
-> 1902 rval = grad(expr[idx],
1903 inp,
1904 consider_constant=consider_constant,
1905 disconnected_inputs=disconnected_inputs)
1906 rvals.append(rval)
1907 return rvals

File *\lib\site-packages\theano\gradient.py:589, in grad(cost, wrt, consider_constant, disconnected_inputs, add_names, known_grads, return_disconnected, null_gradients)
586 for elem in wrt:
587 if elem not in var_to_app_to_idx and elem is not cost \
588 and elem not in grad_dict:
--> 589 handle_disconnected(elem)
590 grad_dict[elem] = disconnected_type()
592 cost_name = None

File *\lib\site-packages\theano\gradient.py:576, in grad..handle_disconnected(var)
574 elif disconnected_inputs == 'raise':
575 message = utils.get_variable_trace_string(var)
--> 576 raise DisconnectedInputError(message)
577 else:
578 raise ValueError("Invalid value for keyword "
579 "'disconnected_inputs', valid values are "
580 "'ignore', 'warn' and 'raise'.")

DisconnectedInputError:
Backtrace when that variable is created:

File "*\lib\site-packages\IPython\core\interactiveshell.py", line 3203, in run_cell_async
has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
File "*\lib\site-packages\IPython\core\interactiveshell.py", line 3382, in run_ast_nodes
if await self.run_code(code, result, async_=asy):
File "*\lib\site-packages\IPython\core\interactiveshell.py", line 3442, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "C:\Users\YN\AppData\Local\Temp\ipykernel_15448\4013410499.py", line 34, in
conv_output = nn.layers.get_output(layer_name, sym_x, deterministic=True) #Conv1DLayer
File "*\lib\site-packages\lasagne\layers\helper.py", line 197, in get_output
all_outputs[layer] = layer.get_output_for(layer_inputs, **kwargs)
File "*\lib\site-packages\lasagne\layers\conv.py", line 352, in get_output_for
conved = self.convolve(input, **kwargs)
File "*\lib\site-packages\lasagne\layers\conv.py", line 511, in convolve
conved = self.convolution(input, self.W,
File "*\lib\site-packages\lasagne\theano_extensions\conv.py", line 75, in conv1d_mc0
return conved[:, :, 0, :] # drop the unused dimension



Am I missing something? Is there is a way to get this gradient computation to work?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to create a custom Layout which will be displayed as floating element in jetpack compose?

 Programing Coderfunda     December 02, 2023     No comments   

I have requirement to create a component which will be displayed by the nested child component but it should not be constrained inside to any it's parent component. And I can position it like top, bottom, end, start. It's exactly like Dialog but more customized and I should be able to interact content behind this floating layout. Can we achieve this type of requirement in jetpack compose ??
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Subtitles file in the Video

 Programing Coderfunda     December 02, 2023     No comments   

When creating the player, I ran into a problem:




To use this code, you need to have a file with subtitles, but it so happened that subtitles are EMBEDDED IN THE VIDEO CODE, that is, subtitles are in the video, but there is no file with them (because I downloaded it)


How to solve this problem?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

01 December, 2023

React Native Android biometrics - can I locally authenticate using face lock? From what I see, only fingerprint authentication works

 Programing Coderfunda     December 01, 2023     No comments   

I can set a fingerprint and a face unlock on my Android phone and currently I am trying to check if either is available and biometrically authenticate the user in my application.


I am currently using the react-native-biometrics package which supports both TouchID and FaceID for iOS, but only Biometrics for Android. When I do this:
const { biometryType } = await biometrics.isSensorAvailable();



It is only defined if I have a fingerprint unlock set up.
const { success } = await biometrics.simplePrompt({
promptMessage: 'Confirmation',
});



Also only triggers if I have fingerprint unlock set up. It doesn't do anything if I just have face unlock set up.


From what I can see, all React Native libraries that I have found only support fingerprint for Android. I imagine there must be some sort of Android reason for this?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

In MacOS, can I control a window's location automatically?

 Programing Coderfunda     December 01, 2023     No comments   

When I'm waiting for a webinar with Zoom on MacOS, there's a Zoom bug that the 'Webinar will start shortly' window keeps jumping into the middle of the screen every minute and cannot be prevented from doing that.


If I were using Linux/X, I would be able to tell the window manager to recognise this window and keep it in the corner, or offscreen, or something.


All the web searching I've done comes up with how to keep windows on top - nearly the opposite of what I want.


The closest I've found to a solution is setting Zoom in the Icon Bar to 'Options > Assign to: all desktops' which (bizarrely) hides all the zoom windows underneath all other windows if I'm not actively using it... except, of course, for the one I'd actually like to hide.


Obviously the correct solution is to become massively wealthy, buy Zoom, and force them to fix their damn software. Or buy Apple and force them to rename themselves X and... oh, wait, that's something else.


Is there something I can do to prevent this 'Webinar is almost ready to start' popup from... uh, popping up?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to resize the console window and move it to fill the screen

 Programing Coderfunda     December 01, 2023     No comments   

I am using C++ in Visual Studio 2017, and I am making a text based game in the console window.


When I run my program, and it opens the console window, I want it to automatically go into full screen mode.


Here is my current attempt, where it resizes the console window, but it doesn't move to fill the screen and goes off of the edge
#include

int main()
{
HWND window = GetDesktopWindow();
HWND console = GetConsoleWindow();
RECT r;

if (GetWindowRect(window, &r))
{
int width = r.right - r.left;
int height = r.bottom - r.top;
MoveWindow(console, 0, 0, width, height, TRUE);
}
}



When I run it, the console window opens to a random spot on the screen as normal, but then it grows to the size of the full screen, but the top left corner doesn't move.


When I run the program
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to resize a cylinder from one end and move it backwards in Roblox

 Programing Coderfunda     December 01, 2023     No comments   

I'm making a cigarette in Roblox and I want it to work correctly


it made the cig resize to the front.


you can get it yourself here:

https://filetransfer.io/data-package/qKBHvHxS#link />

and for people who want the code all you really need to see is this:
for i = bit.Size.X, 0, -0.1 do
local tweenInfo = TweenInfo.new(0.1)
local goal = {}
goal.Size = Vector3.new(i, bit.Size.Y, bit.Size.Z)
local tween = TweenService:Create(bit, tweenInfo, goal)
tween:Play()
wait(0.1)
bit.CFrame = bit.CFrame + bit.CFrame.LookVector * -0.1
end



But seriously, I do recommend downloading the RBXM file and actually testing it.


Also its a tool, so this accounts for rotations.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Reference Document for Laravel / Filament

 Programing Coderfunda     December 01, 2023     No comments   

Hello all - I am so much loving Laravel and Filament - been looking at Laravel and somewhat used it a couple years back - but now with Laravel 10, Filament 3, LiveWire, PhpStorm, GitHub CoPilot - it all comes together to make the coding so good, I want to code more.

I love to read the docs and I always have now laravel docs and filament docs open in tabs at all times - though google sometimes takes to the docs pages which are for older laravel and filament, but its fine.

I am trying to see if there is a Laravel and/or Filament Reference Document website ? a palce which would list all classes, their methods and properties - for now, I am diving into the code files trying to figure out what is available and also relying on the auto complete list in PhpStorm, but maybe a separate document where I can do CTRL+F would be great. submitted by /u/zaidpirwani
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

30 November, 2023

How to switch off output logs relating style sheet?

 Programing Coderfunda     November 30, 2023     No comments   

When I run my application, I have many extra logs in Qt Creator "Application Output" tab:
[qss_ld] "loading style sheet file \"titlebardockinactive.qsse\"."
[qss_ld] "style sheet file resolved in the default path: \":/styles/blacktheme/titlebardockinactive.qsse\"."
[qss_ld] "processing style sheet file \":/styles/blacktheme/titlebardockinactive.qsse\"."
[qss_ld] "importing style sheet file \"variable.qsse\"."



How can I switch off this output logs?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

IIS Reverse Proxy Rewrite Module is gibing 404 service not found error

 Programing Coderfunda     November 30, 2023     No comments   

I have a service which i want to rewrite the masked url is :

https://my_domain_name:my_port_no/uri_part. /> It is working when i request it through iis server directly.
But when i rewrite this using reverse proxy and set up an inbound rule only
then it is showing service not found 404 error in postman. Here's the rewritten url which i want to hit



http://iis_server_ip:iis_server_port/uri. />

I have choosen rever proxy for url rewrite and and created an inbound rule wherein i have put the masked url. I am fairly new to iis and its application. Can anyone tell me what could be the issue.


I tried requesting through rewritten url and it was showing 404 service not found error.
I am able to connect to the domain from my iis server as telnet is working. Also using actual url i am able to get the response but when i rewrite and then request it is showing 404 service not found error. Also i am not sure if i should implement an outboun rule as well or not in reverse proxy.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

compare two array and exclude the common one and show the result

 Programing Coderfunda     November 30, 2023     No comments   

my first array contains line of strings(this list contains 456454), which needs to be compared with an array(456454, 456789).


$unprotected - "this list contains 456454" $blocklist - @('456454', '456789')


foreach ($ele in $blocklist)
{
foreach ($elem in $unprotected)
{
if ($ele -contains $elem)
{}
else {$var_chk = "1"}
}
} if($var_chk = "1"){$Arr_lst += $elem}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

When does a kafka connect SourceTask fail?

 Programing Coderfunda     November 30, 2023     No comments   

I am looking into emitting metrics when a SourceTask fails for specific reasons only, my current understanding is that whenever start or poll encounters an unhandled exception source task enters failed state.


This got me curious about the lifecycle of a SourceTask.


is my understanding correct? can it fail for reasons when poll doesn't throw any error?


also would every instance of "entering into failed state" trigger the stop method within the SourceTask or can it happen that stop isn't triggered?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to replace unicode characters in string with something else python?

 Programing Coderfunda     November 30, 2023     No comments   

I have a string that I got from reading a HTML webpage with bullets that have a symbol like "•" because of the bulleted list. Note that the text is an HTML source from a webpage using Python 2.7's urllib2.read(webaddress).



I know the unicode character for the bullet character as U+2022, but how do I actually replace that unicode character with something else?



I tried doing
str.replace("•", "something")



but it does not appear to work... how do I do this?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

29 November, 2023

What is causing my connection to my sql server not to connect?

 Programing Coderfunda     November 29, 2023     No comments   

My bartering app that reads from a sql server database freezes at connection_1.open .[[[[enter image description here](
https://i.stack.imgur.com/oPKGp.png)](https://i.stack.imgur.com/1xvaS.png)](https://i.stack.imgur.com/h3Izl.png)](https://i.stack.imgur.com/tvPNA.png) />

I was expecting the connection to go through.


What causes the above error?


Please help
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Reset 3 Slicers to Select All when in a 4th slicer 'Yes' or 'No' selected

 Programing Coderfunda     November 29, 2023     No comments   

I'm pretty new to PBi and seem to have an opportunity that I can't find a solution for.
I have 4 slicers for 4 flags (a Yes or No value) to display whether a patient has Condition 1, Condition 2 etc. As these 4 conditions aren't mutally exclusive, a patient could have 2 or more conditions, how can I reset 3 slicers to Select All when a 'Yes' or 'No' is selected in a 4th slicer?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Is there a online FTP i can put on my website?

 Programing Coderfunda     November 29, 2023     No comments   

Im trying to find something so that i can modify, delete etc my code on the web. Do y'all have any good ones you recommend? Im trying to find it because i have a co-dev that cant access my server for some reason.


I tried googel/youtube searching it but found nothing
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Problem with saving data to a file, the file is left blank most of the time **EDIT i dont really understand, im relatively new to this [duplicate]

 Programing Coderfunda     November 29, 2023     No comments   

I have made a program which is trying to save data to a file however when i try to save it it doesnt go into the file the way i expected it to.
from tkinter import *
from tkinter import messagebox

addPupil = Tk()
addPupil.geometry("275x200")
addPupil.title("Add Pupil")

Label(text = "Add New Pupil", width = 30).grid(columnspan = 3)

x = 1
y = 0

entryboxNames = ["First Name", "Last Name", "School Name", "Guardian Name", "Gender"]

for i in range(5):
Label(text = entryboxNames[i]).grid(row = x, column = y)
ent = Entry()
Entry().grid(row = x, column = y + 1)
x = x + 1

def save():
file = open("details.txt", "a")
file.write(entryboxNames[i] + ":" + ent.get() + " " + "\n\n")
messagebox.showinfo("Saved", "Data saved")
file.close

save = Button(text = "Save", command = save).grid(row = 6, column = 0)



for some reason this code isnt saving data to the file, all i can see is the final term (gender) with nothing after it even if anyone enters something
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Login for access token 422 Validation Error FastApi

 Programing Coderfunda     November 29, 2023     No comments   

I want make autorization on my site using this code (It is not important for me to use this particular authorization option. If you have other options for implementing authorization on the site, I will be glad to consider them)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

SECRET_KEY = "somekeyfasfascsacs"
ALGORITHM = "HS256"

bcrypt_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_bearer = OAuth2PasswordBearer(tokenUrl="auth/token")

db_dependency = Annotated[Session, Depends(get_db)]

def authenticate_user(username: str, password: str, db: db_dependency):
user = db.query(Users).filter(Users.username == username).first()
if not user:
return False
if not bcrypt_context.verify(password, user.hashed_password):
return False
print(type(user))
return user

def create_access_token(username: str, user_id: int,
expires_delta: Optional[datetime.timedelta] = None):

encode = {"sub": username, "id": user_id}
if expires_delta:
expire = datetime.datetime.utcnow() + expires_delta
else:
expire = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
encode.update({"exp": expire})
return jwt.encode(encode, SECRET_KEY, algorithm=ALGORITHM)

async def get_current_user(token: Annotated[str, Depends(oauth2_bearer)]):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
user_id: int = payload.get("id")
user_role: str = payload.get("role")
if username is None or user_id is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user")
return {"username": username, "id": user_id, "user_role": user_role}
except JWTError:
# When authorizing using a button and trying to use other functions,
# it gives this error
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user")

@router.post("/token")
async def login_for_access_token(response: Response, form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)):

user = authenticate_user(form_data.username, form_data.password, db)
if not user:
return False
token_expires = datetime.timedelta(minutes=60)
token = create_access_token(user.username,
user.id,
expires_delta=token_expires)

response.set_cookie(key="access_token", value=token, httponly=True)

return True



But I get this error:





If you log in through the Autorize button, it doesn’t give you an error, but when you try to use other functions, the site gives you a 401 Unautorize error.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

11 November, 2023

Access a Json inside a string?

 Programing Coderfunda     November 11, 2023     No comments   

Suppose I have a single dictionary/Json in Python which is inside a List:


Minimum Working Example:
response = [{ "UserStor": "id1","StoryTitle": "title1","StoryState": "state1", "UserStoryType": "type1","RawUpdates": "updates1","RawComments": "comments1"}]



If I need to access this dictionary, I can do:
print(response[0])

#output
{'UserStor': 'id1', 'StoryTitle': 'title1', 'StoryState': 'state1', 'UserStoryType': 'type1', 'RawUpdates': 'updates1', 'RawComments': 'comments1'}


---



Now, I have another dictionary but, it is inside a string
response = "{'UserStor': 'id1', 'StoryTitle': 'title1', 'StoryState': 'state1', 'UserStoryType': 'type1', 'RawUpdates': 'updates1', 'RawComments': 'comments1'}"



How, can I access this dictionary?


I know I can use ast.literal_eval().


Is there any other way to access this dictionary without using literal_eval()/eval() ?


I am here to learn, your comments and answers are welcome.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Add tag to another tag that matched condition

 Programing Coderfunda     November 11, 2023     No comments   

In this case, i just want to add just before , but i don't want to add that already has before . What to to add or edit from the below Regex?
$string = "One two three four five six seven";
Result i want : One two three four five six seven

$xx = preg_replace_callback(
'//',
function ($addtag) {
return "".$addtag[0];
},
$string
);

echo $xx;



Result i want : One two three four five six seven
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

No module named - Running script from Terminal/IronPython [duplicate]

 Programing Coderfunda     November 11, 2023     No comments   

When I try to open a scrpit using IronPython, I get an error: No module named 'config'


File structure for python project:



Root



ConfigGenerator



__config_generator.py







config.py




__config_generator.py:
import config

CONFIG = config.Config()

def __main():
# there are redundant to the question code

if __name__ == '__main__':
__main()



And now C# project:
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using System;
using System.Windows.Forms;

namespace ProjectName
{
public partial class MainForm : Form
{
private ScriptEngine _engine;

public MainForm()
{
_engine = Python.CreateEngine();

InitializeComponent();
}

private void StartConfigGenerator_Click(object sender, EventArgs e)
{
RunScript(@"Q:\Project\Python\Bots\Root\ConfigGenerator\__config_generator.py");
}

private void RunScript(string path)
{
_engine.ExecuteFile(path);
}
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Java SWT: Difference between redraw, reskin, update and requestLayout (and pack)

 Programing Coderfunda     November 11, 2023     No comments   

Can anybody please explain to me the difference of the methods Control.redraw(), Control.update(), Widget.reskin(), Control.requestLayout() and Control.pack()?
Unfortunately the API documentation does not tell so much about the differences.


I guess the following:


Control.requestLayout() means calculating the size and position of a control inside a Composite when its content (like a text in a label or text field) has changed and perhaps its displayed size/position is not anymore appropriate.
I think I understand Control.pack(): It is just a part of Control.requestLayout or rather Composite.layout() as only the size of controls will be changed but not the position.


Control.redraw() and Control.update(): It seems to me that both methods just paint the control again and you call them when the operating system does not show it correctly anymore. You call the methods if size and position have not changed. The difference between both methods is that update() repaints the control immediately whereas redraw() can do it after some time.


I don't understand when I need to call Widget.reskin(). It seems to me the same as Control.redraw().
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Optimization dots&line game

 Programing Coderfunda     November 11, 2023     No comments   

i just built dots and line game with minimax algorithm where user could play with AI, but unfortunately it is too slow even in just depth 4. so any optimization technique?


here My code,
class Maze {
constructor(gridX, gridY, sideSize) {
this.board = Array.from({ length: gridY }, (a) => a = Array.from({ length: gridX }, (b) => b = Array.from({ length: 4 }, c => c = 0)));
this.visited = [];
this.gap = Math.floor(sideSize / 8);
this.x = gridX;
this.y = gridY;
this.winPointX = 0;
this.winPointY = 0;
this.row = gridX * this.gap;
this.column = gridY * this.gap;
this.sideSize = sideSize;

};
drawGrid(ctx) {
console.log(this.row, this.column)
ctx.clearRect(0, 0, canv.width, canv.height);
for (let x = 0; x < this.row; x += this.x)
for (let y = 0; y < this.column; y += this.y) {

ctx.fillStyle = 'red';
ctx.fillRect(x * this.gap, y * this.gap, this.gap, this.gap);

}

};
ai(depth, alpha, beta, player, advantage, y, x, tile_Y, tile_X) {
if (y !== undefined && x !== undefined) {
let winPoint = this.boxForm(y, x)
if (tile_X > -1 && tile_X < 8 && tile_Y > -1 && tile_Y < 8) {
winPoint = winPoint || this.boxForm(tile_Y, tile_X)
}

if (winPoint && player == 'O') {
player = 'X';

advantage += 10

}
else if (winPoint && player == 'X') {
player = 'O';

advantage -= 10;

// console.log('Human bonus',y,x)
}
}

if (depth === 0) {

return { score: advantage }
}

var pieceArr = [];

for (var i = 0; i < this.board.length; i++) {
for (var j = 0; j < this.board[0].length; j++) {

for (let b = 0; b < 4; b++) {
if (this.board[i][j][b]) {
continue;
};
let tileX = j;
let tileY = i;
let best = {}
this.change(i, j, b)
best.bestmove = [i, j, b];
let neghdir;
if (b == 2) {
neghdir = 0;
tileX++
} else if (b == 0) {
neghdir = 2;
tileX--
} else if (b == 3) {
neghdir = 1;
tileY--
} else {
neghdir = 3;
tileY++
};
if (tileX > -1 && tileX < 8 && tileY > -1 && tileY < 8) {
this.change(tileY, tileX, neghdir);
}
var g = this.ai(depth - 1, alpha, beta, player == 'X' ? 'O' : 'X', advantage, i, j, tileY, tileX);

/* if (tileX>-1&&tileX-1&&tileY alpha) {
alpha = best.score;
}
} else {

if (best.score < beta) {
beta = best.score
}
};
if (tileX > -1 && tileX < 8 && tileY > -1 && tileY < 8) {
this.board[tileY][tileX][neghdir] = 0;
}
this.board[i][j][b] = 0;
pieceArr.push(best)

if (alpha >= beta) {
break;

}

}

}
};
pieceArr.sort((a,b)=>{
return Math.random()-0.5;
})
var bestMove;
if (player === 'X') {
var bestScore = -10000;
for (var i = 0; i < pieceArr.length; i++) {
if (pieceArr[i].score > bestScore) {
bestScore = pieceArr[i].score;
bestMove = i;
}
}
} else {
var bestScore = 10000;
for (var i = 0; i < pieceArr.length; i++) {
if (pieceArr[i].score < bestScore) {
bestScore = pieceArr[i].score;
bestMove = i;
}
}
}
return pieceArr[bestMove];
};
rmSide(side, dir, col) {
let vertex;
if (dir == 'w') {
vertex = [side[0] * this.x, this.y * side[1]];
} else if (dir == 'e') {
vertex = [(side[0] + 1) * this.x, this.y * side[1]];
}
else if (dir == 'n') {
vertex = [this.x * side[1], (side[0]) * this.y];

} else if (dir == 's') {
vertex = [this.x * (side[1] + 1), (side[0]) * this.y];
}
if (!vertex) {
return null
}

let x = vertex[0];

for (let y = vertex[1] + 1; y < vertex[1] + this.y; y++) {

ctx.fillStyle = col;
if (dir == 'n' || dir == 's') {
ctx.fillRect((y) * this.gap, (x) * this.gap, this.gap, this.gap);
} else {
ctx.fillRect((x) * this.gap, (y) * this.gap, this.gap, this.gap);
}

};

}
change(y, x, dir, player) {

this.board[y][x][dir] = 'X';

}
boxForm(y, x) {

for (let i = 0; i < 4; i++) {
if (!this.board[y][x][i]) {
return false
}

};

return true
}
};
//dots and line
const canv = document.getElementById('canv');
const ctx = canv.getContext('2d');
const size = Math.min(window.innerWidth, window.innerHeight) * 0.7;
canv.width = size;
canv.height = size
const sideSize = size / 8;
console.log(sideSize)
let turn = 'X'

const maze = new Maze(8, 8, sideSize);

maze.drawGrid(ctx);
function mve(tileX, tileY, dir, player) {

if (tileX < 8 && tileY > -1 && tileX > -1 && tileY < 8) {

turn = player == 'O' ? 'X' : 'O'

let n = null;
if (dir == 'n') {
n = 3
} else if (dir == 's') {
n = 1
} else if (dir === 'e') {
n = 2
} else {
n = 0
}

/*
let cordX = e.clientX;
let cordY = e.clientY;
let dirCor = {
'n':[65+tileX*(100+20),75+(tileY)*(100+20)],
's':[65+tileX*(100+20),195+(tileY)*(100+20)],
'w':[45+tileX*(100+20),90+(tileY)*(100+20)],
'e':[165+tileX*(100+20),90+(tileY)*(100+20)]

};
console.log(cordX,cordY,dirCor);

// console.log(dirCor['n'][0]&&(dirCor['n'][0]+100)&&dirCor['n'][1]&&(dirCor['n'][0]+15))
if (cordX>=dirCor['n'][0]&&cordX=dirCor['n'][1]&&cordY=dirCor['s'][0]&&cordX=dirCor['s'][1]&&cordY=dirCor['e'][0]&&cordX=dirCor['e'][1]&&cordY=dirCor['w'][0]&&cordX=dirCor['w'][1]&&cordY -1 && tileX < 8 && tileY > -1 && tileY < 8) {
maze.change(tileY, tileX, neghdir);
if (maze.boxForm(tileY, tileX)) {
turn = player;
}
};
if (turn == "O") {
console.log(maze.board)
playAI()
}

}

}
}

function playAI() {

let aimove = maze.ai(4, -Infinity, Infinity, 'X', 0);
let dir1 = undefined;
if (aimove.bestmove[2] == 0) {
dir1 = 'w'
} else if (aimove.bestmove[2] == 1) {
dir1 = 's'
} else if (aimove.bestmove[2] == 2) {
dir1 = 'e'
} else {
dir1 = 'n'
};
console.log(aimove)
mve(aimove.bestmove[1], aimove.bestmove[0], dir1, 'O')

}

canv.addEventListener('click', (e) => {
const rect = canv.getBoundingClientRect()
let tileX = Math.floor((e.clientX - rect.x) / sideSize);
let tileY = Math.floor((e.clientY - rect.y) / sideSize);
let dir = prompt('direction');

mve(tileX, tileY, dir, 'X');

});
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

10 November, 2023

npm install MaxListenersExceededWarning

 Programing Coderfunda     November 10, 2023     No comments   

During npm install I get several of the following warning message:


(node:5156) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxLis
teners() to increase limit
(node:5156) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxLis
teners() to increase limit
npm ERR! code ECONNRESET
npm ERR! syscall read
npm ERR! errno ECONNRESET
npm ERR! network request to
https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz failed, reason: read ECONNRESET
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'


npm ERR! A complete log of this run can be found in: C:\Users\xxxx\AppData\Local\npm-cache_logs\2023-11-10T15_52_29_865Z-debug-0.log


install npm and dependences
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Atomic locks in Laravel (demo & tutorial)

 Programing Coderfunda     November 10, 2023     No comments   

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

How to pass multiple values as sql array for a parameter? (Or how can I cirumvent limit of parameters of prepared statement?)

 Programing Coderfunda     November 10, 2023     No comments   

I'm trying to create a query using QueryDSL wich accepts more than 32767 parameters (32767 is the upper limit of parameters the postgresql driver accepts).


The query is currently created like this:
static final QInvoiceEntity invoiceEntity = ...

void queryInvoicesWithId(String... ids) {
JPAQuery query = ...
query.where(invoiceEntity.id.in(ids));
}



This works if no more than 32767 parameters are passed. If you pass more than that (e.g. 38000) the following exception is thrown:
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 38000
at org.postgresql.core.PGStream.sendInteger2(PGStream.java:275)



One solution according to 1 is to use ANY and pass the parameters as an array. I've tried the following but to no avail:
query.where(Expressions.booleanTemplate("{0} = ANY {1}", invoiceEntity.id, ids);



But this throws the following exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ? near line 3, column 31 [select invoiceEntity
from InvoiceEntity invoiceEntity
where invoiceEntity.id = ANY (?1)



I've even tried to pass the parameters as a string and convert it back in the query:
query.where(Expressions.booleanTemplate("{0} = ANY string_to_array({1}, ',')", invoiceEntity.id, String.join(",", ids));



But this throws the following exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 3, column 45 [select invoiceEntity
from InvoiceEntity invoiceEntity
where invoiceEntity.id = ANY string_to_array(?1, ',')
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to get the cell's output data from a azure databricks notebook to a file

 Programing Coderfunda     November 10, 2023     No comments   

Unable to get a single cell's output to a file in Azure databricks notebook


Tried many ways but unable to get the result.


Can someone help me on this if there is a way or there is no way please let me know.


Thanks and regards,
Prem
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Getting an image from the database using path images on the client side

 Programing Coderfunda     November 10, 2023     No comments   

I used multer to download the image and save the path of the image to the database, and then how can I get the image from the client and show it on the screen?
import multer from 'multer';

const storageConfig = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './images')
},

filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname)
}
})

const upload = multer({storage: storageConfig});

let path = '';

app.post('/upload',upload.single('image'), (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '
http://localhost:3000'); /> if(req.file) {
console.log(req.file);
path = req.file.path;
res.send('hi')
return;
}
res.send('bye')
})



after I received the file path I saved it in the database, but I don’t know how to use it later to show this picture on the screen
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

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

Categories

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

Social Media Links

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

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

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

Loading...

Laravel News

Loading...

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