07 June, 2024
06 June, 2024
Confused about how to use Microsoft.AspNetCore.SystemWebAdapters while trying to port from old ASP.NET website to new ASP.NET Core web app
Programing Coderfunda June 06, 2024 No comments
Program.cs:
using OldHandlers;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSystemWebAdapters(); // Register SystemWebAdapters
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// Register SystemWebAdapters middleware
app.UseSystemWebAdapters();
// Define endpoints
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/myhandler", async context =>
{
var adapter = new AspNetCoreHttpContextAdapter(context);
var handler = new MyHandler();
handler.ProcessRequest(adapter);
});
});
app.UseAuthorization();
app.MapRazorPages();
app.Run();
And I have:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SystemWebAdapters;
using System.Threading.Tasks;
using OldHandlers;
public class AspNetCoreHttpContextAdapter : IHttpContextAdapter
{
private readonly HttpContext _context;
public AspNetCoreHttpContextAdapter(HttpContext context)
{
_context = context;
}
public string ResponseContentType
{
get => _context.Response.ContentType;
set => _context.Response.ContentType = value;
}
public void WriteResponse(string content)
{
_context.Response.WriteAsync(content);
}
public async Task ReadRequestBodyAsync()
{
using (StreamReader reader = new StreamReader(_context.Request.Body))
{
return await reader.ReadToEndAsync();
}
}
public void SetStatusCode(int statusCode)
{
_context.Response.StatusCode = statusCode;
}
public object GetRouteData(string key)
{
return _context.Items[key];
}
}
In my old website, I created a new handler:
public class MyHttpHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
var adapter = new SystemWebHttpContextAdapter(new HttpContextWrapper(context));
var handler = new MyHandler();
handler.ProcessRequest(adapter);
}
public bool IsReusable => false;
}
and:
using System.IO;
using System.Threading.Tasks;
using System.Web;
using OldHandlers;
public class SystemWebHttpContextAdapter : IHttpContextAdapter
{
private readonly HttpContextBase _context;
public SystemWebHttpContextAdapter(HttpContextBase context)
{
_context = context;
}
public string ResponseContentType
{
get => _context.Response.ContentType;
set => _context.Response.ContentType = value;
}
public void WriteResponse(string content)
{
_context.Response.Write(content);
}
public async Task ReadRequestBodyAsync()
{
using (StreamReader reader = new StreamReader(_context.Request.InputStream))
{
return await reader.ReadToEndAsync();
}
}
public void SetStatusCode(int statusCode)
{
_context.Response.StatusCode = statusCode;
}
public object GetRouteData(string key)
{
return _context.Items[key];
}
}
I also created a .NET Standard 2.0 library to contain the concrete handler implementation:
namespace OldHandlers
{
public class MyHandler
{
public void ProcessRequest(IHttpContextAdapter context)
{
context.ResponseContentType = "text/plain";
context.WriteResponse("Hello, World!");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace OldHandlers
{
public interface IHttpContextAdapter
{
string ResponseContentType { get; set; }
void WriteResponse(string content);
Task ReadRequestBodyAsync();
void SetStatusCode(int statusCode);
object GetRouteData(string key);
}
}
What I don't understand is that, if I use Microsoft.AspNetCore.SystemWebAdapters, then do I need to create my adapter classes, AspNetCoreHttpContextAdapter and SystemWebHttpContextAdapter?
Laracord: Create Discord bots with Laravel
Programing Coderfunda June 06, 2024 No comments
I set out to make a Discord bot late last year quickly matching DiscordPHP with Laravel Zero. While it was pretty easy to get up and rolling, it quickly became clear that DiscordPHP, being a raw library structured around the Discord API, was missing some serious DX leaving a lot to be desired.
In January I decided to abstract what I had so far and do an initial release. Fast-forward a few months and Laracord has grown far past what I initially had in mind. It is packed with features and I think it is turning out to be pretty fun to use!
If this sounds like your cup of tea, I'd love for you to check it out:
Features
* Out of the box support for databases, caching, and many other Laravel features.
* Instantly generate working bot commands and event listeners with 0 knowledge.
* Automatic handling of registering/updating/unregistering application slash commands.
* Easy to use interaction routing for persistence on message buttons and actions.
* Generate asynchronous services/tasks that run parallel to the bot.
* Optional HTTP Server with native Laravel routing and Livewire support.
* Fully configurable and extendable.
* Beautiful console logging with timestamps.
* Fully documented and maintained.
Documentation
* Website:
https://laracord.com
/> * Docs:
https://laracord.com/docs
/> * Discord:
https://laracord.com/discord
/>
submitted by /u/Log1x
[link] [comments]
Laravel fatigue - want to try something else
Programing Coderfunda June 06, 2024 No comments
But I'm finding myself a little fatigued with it - like I want to 'try something else' for building a small app. Any other Laravel devs ever been in a similar boat? Where did you end up? Django? Flask? Node? - just curious - looking for something 'fresh' to use for my next project. submitted by /u/jusjohns82
[link] [comments]
Dereferencing an l-value
Programing Coderfunda June 06, 2024 No comments
_device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(byteSize),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(defaultBuffer));
When I try to reproduce this code in my project, I get this error: C2102 '&' requires l-value.
I have brief understanding of all r/l -value stuff (though I am no expert).
Function signature:
HRESULT CreateCommittedResource( const D3D12_HEAP_PROPERTIES *pHeapProperties, D3D12_HEAP_FLAGS HeapFlags,
const D3D12_RESOURCE_DESC *pDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
REFIID riidResource,
_COM_Outptr_opt_ void **ppvResource)
The error, obviously, is about the 1st and the 3rd parameters.
As far as I understand, calling a class constructor within function call scope creates a temporary variable which expires as soon as the the execution flow moves to the called function body, so using a pointer to it within the function body is wrong (it "points" to a destructed value).
What's more surprising, I have obtained the guidebook sample code. I compiled it and it's OK, there are no errors. Moreover, the program runs OK (everything is drawn properly), so my thoughts on dangling pointer were wrong. I want to understand the thing and hear opinion from an experienced coder.
I suspect that maybe some errors have been suppresed via ProjectSettings. Or else, it has to do something with out-dated SDK version or older compiler (v140) I had to install to run the sample.
I can apply sample code if necessary.
05 June, 2024
Tough job market?
Programing Coderfunda June 05, 2024 No comments
Larajobs is great but I haven’t been hearing back— some when I go through the process, they make a comment that they have interviews booked “all day”
I’m not seeing a ton of Laravel listings as there were 2-3 years ago. Just curious if anyone else is experiencing the same? Just a saturated market or what?
(Obviously not looking for a job over Reddit, just for other opinions) submitted by /u/Adventurous-Bug2282
[link] [comments]
First-party support for Sentry in Forge
Programing Coderfunda June 05, 2024 No comments
Laravel Pennant: first-party feature flags
Programing Coderfunda June 05, 2024 No comments
Why does `placeholder-shown:no-underline` work but `placeholder:no-underline` doesn't?
Programing Coderfunda June 05, 2024 No comments
Example:
https://play.tailwindcss.com/gZIVyRDi6y
Laravel Packages - Variable Validation & Sanitization
Programing Coderfunda June 05, 2024 No comments
There is no magic bullet built-in functionality that does that, right? I'm using the "Validator" package in combination with strip_tags(Purifier::clean($var) and I already added both of them to my custom-built controllers. I'm left wondering if that was wasteful and I'm particularly concerned about any outside packages I'm using.
If I need to add some code to the outside packages, then that would mean re-adding it every time they update/we adopt a package too, correct?
Thoughts and suggestions for best practices? submitted by /u/altdevD
[link] [comments]
04 June, 2024
Why do I get an Invalid Argument Exception when displaying a network image?
Programing Coderfunda June 04, 2024 No comments
Widget displayImage(BuildContext context, MyBook book) {
if (book.coverUrl != null) {
try {
return Image.network(book.coverUrl!,
errorBuilder: (context, error, stackTrace) {
return Text('No \nimage');
});
} on Exception {
return Text('No \nImage');
}
} else {
return Text('No \nImage');
}
}
I receive the message
════════ Exception caught by image resource service ══════════════════
Invalid argument(s): No host specified in
URI file:///home/alan/FlutterProjects/books/null
═══════════════════════════════════════════════════════
(file:///home/alan/FlutterProjects/books/ is my app's path. book.coverUrl is a String.)
The online image displays properly, despite the Exception message.
What causes this? Do I need to fix it?
EDIT:
The end of the stack track also includes the message:
Image provider: NetworkImage("null", scale: 1.0)
Image key: NetworkImage("null", scale: 1.0)
Autohotkey - Is there a way to replace every string typed?
Programing Coderfunda June 04, 2024 No comments
I.e
Hey, I'm writing to you to... -> Quack, Quack quack quack quack quack
additionally, I want to add on a random number service that allows me to randomize each string into pre-selected options, though I think I can handle that on my own once I understand how to replace every string first
I.e
Hey, I'm writing to you to... -> Quack, Snack quack flack flack snack
Looking through the autohotkey documentation, I'm only able to find out ways to replace specific strings and inputs into other inputs. Is there a way to allow every string to be translated into one singular output?
UInt16_t multiplication, SAM D21/DA1 microcontroller [closed]
Programing Coderfunda June 04, 2024 No comments
/**
* Convert a value from 0 to 255 to a 1.0 ms
* to 2.0 ms positive PWM cycle based on
* the clock configuration of the TC.
*/
void pwm_lamp_update(int index, uint8_t lamp_user)
{
uint16_t lamp = 0;
lamp = (240 * (uint16_t)lamp_user);
if (0 == index)
{
//lamp0_intensity = ((1175 * (uint16_t) lamp_user) / 100) + 3008;
//lamp0_intensity = lamp0_intensity * 2;
}
else if (1 == index)
{
//lamp1_intensity = ((1175 * (uint16_t) lamp_user) / 100) + 3008;
//lamp1_intensity = lamp1_intensity * 2;
//lamp1_intensity = 240;
//lamp1_intensity = 65500;
//lamp1_intensity = 31680;
//lamp1_intensity = (240 * (uint16_t)lamp_user);
lamp1_intensity = lamp;
lamp1_intensity = 41520;
}
lamp_user = lamp_user;
}
lampx_intensity is an uint16_t.
The first two lines of the if statements are code that creates a servo PWM type signal. I am trying to make a power PWM signal.
I find that if I hard code a number everything works fine. Anytime that I use a variable I don't get any output.
In the example above, even 'lamp1_intensity = lamp;' fails. I see a valid value for lamp1_intensity. The live microcontroller is not throwing any errors that I see. The light is not working and there isn't any PWM signal when it fails.
The microcontroller is an AT03259 SAM D21/DA1.
Encrypt with Prune, Dispatch without Delay & Prohibitable
Programing Coderfunda June 04, 2024 No comments
Issue while getting data from Ringba API using Google Apps Script
Programing Coderfunda June 04, 2024 No comments
function fetchRecordingData(spreadsheet, specificBuyerName) {
var ringbaSheet = spreadsheet.getActiveSheet();
var dateValue = ringbaSheet.getRange("K1").getValue();
var targetDate = new Date(dateValue);
var startOfDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate(), 0, 0, 0);
var endOfDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate(), 23, 59, 59);
var reportStart = new Date(startOfDay.getTime());
var reportEnd = new Date(endOfDay.getTime());
var url = "
https://api.ringba.com/v2/{{account id}}/calllogs";
const apiToken = '###';
var extractedData = [];
var offset = 0;
var size = 1000;
while (true) {
var payload = {
"reportStart": reportStart, //Fri May 31 2024 00:00:00 GMT-0600 (Mountain Daylight Time)
"reportEnd": reportEnd, //Fri May 31 2024 23:59:59 GMT-0600 (Mountain Daylight Time)
"orderByColumns": [],
"filters": [],
"formatDateTime": true,
"formatPercentages": true,
"formatTimeZone": "America/Denver",
"formatTimespans": true,
"offset": offset,
"size": size,
"valueColumns": [
{ "column": "callDt" },
{ "column": "campaignName" },
{ "column": "publisherName" },
{ "column": "inboundPhoneNumber" },
{ "column": "buyer" }
]
};
var options = {
"method": "POST",
"headers": {
"Authorization": "Token " + apiToken,
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8"
},
"payload": JSON.stringify(payload),
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var jsonResponse = JSON.parse(response.getContentText());
var records = jsonResponse.report.records;
if (!records || records.length === 0) {
break;
}
var filteredData = records.filter(function(record) {
return record.buyer && record.buyer.toLowerCase().trim() === specificBuyerName.toLowerCase().trim();
}).map(function(record) {
return [
record.callDt,
record.campaignName,
record.buyer,
record.publisherName,
record.inboundPhoneNumber
];
});
extractedData = extractedData.concat(filteredData);
console.log(extractedData.length);
if (records.length < size) {
break;
}
offset += size;
}
if (extractedData.length > 0) {
var range = ringbaSheet.getRange("A2:E").clearContent();
ringbaSheet.getRange(ringbaSheet.getLastRow() + 1, 1, extractedData.length, extractedData[0].length).setValues(extractedData);
}
There are total of 831 records for that given date, when I run randomly it gives the correct number of records. However, when I run it 2-3 times in quick succession, the number of records in output keeps changing (825,837).
Then I wait for 5-10 minutes, run it, and it gives the correct output (831) again. I am unclear why doesn't it always give the same output. Any guidance to point out my mistake would be much appreciated.
03 June, 2024
Spring Security PreAuthorize using multi-value enum
Programing Coderfunda June 03, 2024 No comments
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@PreAuthorize("hasAuthority('SCOPE_{scope.getName()}') || hasAuthority('SCOPE_{ADMIN_SCOPE.getName()}')")
public @interface RequiredScope {
ServiceScope scope();
static final ServiceScope ADMIN_SCOPE = ServiceScope.SUPERADMIN;
}
I want to be able to pass in a required scope, but also have the superadmin scope be valid too. However, even when the proper authorities are present in the provided token, I get a 403 response stating that I have insufficient scopes.
The error says error="insufficient_scope",error_description="The request requires higher privileges than provided by the access token.",error_uri="
https://tools.ietf.org/html/rfc6750#section-3.1 when making a call to the endpoint via a Swagger page with a valid token provided.
The enum in question is structured as follows with various different scopes (not included)
@Getter
public enum ServiceScope {
String name;
String description;
private ServiceScope(String name, String description) {
this.name = name;
this.description = description;
}
}
The value in name is the actual scope in the token, I just need the annotation to pick it up. Fairly new to spring security, so please be kind!
I have referenced
https://docs.spring.io/spring-security/reference/whats-new.html to start, but haven't been able to find more helpful information
Generating AES IV from Rfc2898DeriveBytes
Programing Coderfunda June 03, 2024 No comments
byte[] salt = GenerateRandomBytes(32); // Generates 32 random bytes
using (Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(plainStrPassword, salt)) {
byte[] aesKey = rfc.GetBytes(32);
byte[] iv = rfc.GetBytes(16); // Should I do this or generate it randomly?
}
My question: Is it OK (secure) to generate the iv from Rfc2898DeriveBytes? Or should I generate it randomly using RNGCryptoServiceProvider?
How to monitor process status during process lifetime
Programing Coderfunda June 03, 2024 No comments
Let's say I have executable main.exec and want to store into a file all subprocess which are called during main.exec execution.
$ main.exec &
$ echo $! # and redirect every ps change for PID $! in a file.
Docker json file log driver unescape
Programing Coderfunda June 03, 2024 No comments
It produces a log like this:
{"key": "value"}
This is the output from docker logs . If I check the daemon log of the container from the /var/lib/docker/container/
{"log": {\"key\": \"value\"}}
Is there a way to unescape this in the daemon logs? There is a complex use case which can't be explained for me to use these logs.
Pytorch - sending dataset to cuda breaks the dataloader iterator - TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu()
Programing Coderfunda June 03, 2024 No comments
02 June, 2024
local issuer certificate error uniquely in docker with python
Programing Coderfunda June 02, 2024 No comments
Outside of docker, the app works. I can fetch the same URL inside the docker image of other language app such as dotnet.
I have tried:
* RUN update-ca-certificates
* Install certfi library and manually supply the certificates during making the call
* Manually insert the certificates that comes with certify library in different locations of docker images such as /usr/local/share/ca-certificates/, /etc/ssl/certs/ and RUN update-ca-certificates
* Tried different versions (3.6.9, 3.8.4) and providers (alpine, buster, slim-buster ) of python.
* Setting different env variables such as REQUESTS_CA_BUNDLE, SSL_CERT_FILE etc.
* Use different libraries such as requests, urllib, urllib3
.... and really large number of different things.
It of course works when I turn the verify off, but I want to keep verification.
MongoDB run loop to add incremental index value in array
Programing Coderfunda June 02, 2024 No comments
Like index starts from 0 to array length - 1.
db.collection.aggregate([
{
"$unwind": "$array"
},
{
"$addFields": {
"array.index": {
"$add": [
{
"$ifNull": ["$index", 0]
},
1
]
}
}
},
{
"$group": {
"_id": "$_id",
"array": {
"$push": "$$ROOT.array"
}
}
}
])
Jest - SyntaxError: Cannot use import statement outside a module
Programing Coderfunda June 02, 2024 No comments
However when I move to use jest with "test": "jest --config jest.config.js", I see the below error.
FAIL src/configuration/notifications.test.js
● Test suite failed to run
/var/www/management/node/src/configuration/notifications.test.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import notifications from './notifications';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Weekly /r/Laravel Help Thread
Programing Coderfunda June 02, 2024 No comments
* 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]
There is no resource to build Laravel video call app using only blade and not use 3rd party paid api.
Programing Coderfunda June 02, 2024 No comments
[link] [comments]
01 June, 2024
python manage.py dumpdata Unable to serialize database
Programing Coderfunda June 01, 2024 No comments
python manage.py dumpdata > data.json
However, I receive such a traceback:
CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-4: character maps to
Exception ignored in:
Traceback (most recent call last):
File "C:\Users\Illia\Desktop\MyDjangoStuff\greatkart\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1625, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
How to solve this issue?
A few easy questions from a Laravel beginner.
Programing Coderfunda June 01, 2024 No comments
I want to create a simple admin panel with a rudimentary hierarchy Account > Store > Product Categories > Products and users that I want to assign to them.
I want to also create a public facing front-end for viewing those products.
I want to work with the Tall Stack for the admin panel and InertiaJS + Vue3 for the front-page.
My questions are:
* How do I add the --auth scaffolding in the TALL stack AFTERWARDS? I want to get started on the project and I don't care about the auth for now since most of it is ready anyway, but I don't see anywhere in the documentation how to add it later.
* Is there anything I need to setup for InertiaJS to be able to work in the project when the TALL stack is already configured? Are there any conflicts that I might experience down the line?
* Is there a good/large open source livewire project to get a better look at how people would usually work with Livewire?
* How do I inject a class in a Livewire component? For example, I will have a product page and I would like to have the logic separately in a productService or action or w/e. How would I inject the class? Do I do it in the constructor as usual?
I chose TALL stack for the admin and Inertia for the front-page because I want to learn both of those technologies as I intend to work with laravel mainly in the future. submitted by /u/AlkaKr
[link] [comments]
How to Run a Python File on a Specific Virtual Desktop Only?
Programing Coderfunda June 01, 2024 No comments
Currently, when I execute my Python file using VS Code, the `webbrowser.open()` command opens the browser window on the desktop where I’m currently working, rather than the one where I initially started the program.
How to create a responsive circle with two lines of text in HTML and CSS?
Programing Coderfunda June 01, 2024 No comments
display: flex;
justify-content: center;
align-items: center;
gap: 15px;
}
.circle {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #333;
color: #fff;
font-size: 32px;
font-weight: 600;
border-radius: 50%;
padding: 20px;
aspect-ratio: 1 / 1;
}
2
AP
200,000
AP
Why is the aspect-ratio CSS property not working here? When the text inside is long enough (like if I use 200,000 instead of 2, it is a square aspect ratio perfect circle). But I need it to work when the text is short too.
I want to avoid Javascript and hardcoding any widths or heights, because the circle should be fully responsive to the text inside of it, and be the minimum size required to display it (while also being a square aspect ratio).
Can't connect to a specific wifi with error : unsupported get ioctl on awdl0
Programing Coderfunda June 01, 2024 No comments
_Apple80211AWDLCompatibilityInternal: unsupported get ioctl on awdl0 for APPLE80211_IOC_CURRENT_NETWORK[103]
The first time it happened was random, I was on the internet and connected to the same wifi and then suddenly I didn't have access to the internet and my Mac was asking me to type my password.
By running Ifconfig, I was able to see that, both, awdl0 and llw0 were inactive (which lead to Airdrop and Airplay being unusable). I was able to activate awdl0 back but not llw0
Here are the things that I have tried so far:
* Forget wifi
* Removing the following files:
sudo rm /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist
sudo rm /Library/Preferences/SystemConfiguration/com.apple.wifi.message-tracer.plist
sudo rm /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist
sudo rm /Library/Preferences/SystemConfiguration/preferences.plist
* Reset NVRAM/PRAM
* sudo ifconfig llw0 up (not working, llw0 still inactive)
* Restart in safe mode
* Manually adding the wifi
None of them worked.
I have a 13 inch MacBook Pro M1 Sonoma 14.5 (up to date)
Any ideas ? I want to avoid a factory reset.