Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
7
13
title
stringlengths
6
183
question
stringlengths
26
183k
answer
stringlengths
20
21.3k
codes
listlengths
0
40
technology
stringclasses
9 values
quality_score
float64
5
10.5
source
stringclasses
2 values
tags
listlengths
0
6
score
float64
-12
31.4k
url
stringlengths
39
143
so_79895327
How to debug Laravel 12 Cors (No 'Access-Control-Allow-Origin' header is present on the requested resource)
Apparently CORS just works with Laravel 12, but it doesn't work for me. Starting from scratch, then Simple routes within api.php: simple app.php, does it need a middleware setup, or is it always there? Postman call, works as expected, but as we know, ignores the origins header. What am I missing?
Map like this Your request is if you run it will run like this (default port). if so check this hits if you use Sanctum cookies, then you must set
[ "Route::get('/show/{id}', [EmailController::class, 'show']); Route::post('/search', [EmailController::class, 'search']); Route::post('/search2', [EmailController::class, 'search2']);", "return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', api: __DIR__.'/.....
php
9.62
stackoverflow
[ "php", "laravel", "cors", "laravel-12" ]
9
https://stackoverflow.com/questions/79895327/how-to-debug-laravel-12-cors-no-access-control-allow-origin-header-is-present
so_79857625
Symfony AI: How to add additional models for the LM Studio bridge?
I’m working with Symfony AI and the LM Studio bridge to manage my language models locally. My goal is to add custom models that are not included in Symfony’s default . My YAML configuration looks like this: Even though the model is loaded in LM Studio, Symfony does not detect it . I created a custom : What I understood...
The feature doesn't seem to be documented indeed, set let's dig into the source that parses the configuration file (ai.yaml): After reading the key, the key is processed by to add extra models: According to the code, your ai.yaml file should look something like this:
[ "<?php namespace App\\Service; use Symfony\\AI\\Platform\\Bridge\\Generic\\CompletionsModel; use Symfony\\AI\\Platform\\Capability; use Symfony\\AI\\Platform\\ModelCatalog\\AbstractModelCatalog; final class LMModelCatalog extends AbstractModelCatalog { public function __construct() { $additionalModels = [ 'minis...
php
9.88
stackoverflow
[ "php", "symfony", "artificial-intelligence" ]
11
https://stackoverflow.com/questions/79857625/symfony-ai-how-to-add-additional-models-for-the-lm-studio-bridge
so_79857135
Api Platform DTO is not comprehensible
version symfony 7.4 symfony/object-mapper 7.4 api-platform/symfony 4.2 php 8.4 Describe the problem So I've been reading about the new recommandation for API Platform which is to use and map DTO instead of writing API Platform ressources metadata directly through the Entity. See also https://api-platform.com/docs/core/...
yeah so api platform maintainer soyuka actually admitted . the recommended approach now is Input DTO as resource, output for docs, and do your thing in processor. your problem is that ObjectMapperProvider and ObjectMapperProcessor handle output differently. provider does it right but processor just ignores output entir...
[ "# src/Entity namespace App\\Entity; #[ORM\\Entity(repositoryClass: CompanyRepository::class)] #[ORM\\Table(name: 'company')] class Company { use TimestampableEntity; #[ORM\\Id] #[ORM\\GeneratedValue] #[ORM\\Column(type: Types::BIGINT)] #[Groups(['read:company'])] private ?int $id = null; #[ORM\\Column(type: Types:...
php
9.5
stackoverflow
[ "php", "symfony", "api-platform.com" ]
8
https://stackoverflow.com/questions/79857135/api-platform-dto-is-not-comprehensible
so_79854613
Symfony ObjectMapper fails on relational property
Everything works perfectly fine for flat structures. However I can't get the Author serialized in underneath API call on . They do describe Recursion over here: https://symfony.com/doc/current/object_mapper.html#handling-recursion but it does not seem to fit underneath implementation. Any ideas on this?! PHP 8.3, Symfo...
Here is a simple test that reproduces your issue: Output: You can fix it by annotating the class like this: Output:
[ "class Book implements EntityInterface { use IdentifiableEntity; #[Column(type: Types::STRING, length: 180)] private string $title; #[ManyToOne(targetEntity: Author::class)] #[JoinColumn(referencedColumnName: 'id', nullable: true)] private ?Author $author; }", "class Author implements EntityInterface { use Identi...
php
7.62
stackoverflow
[ "php", "symfony", "dto", "api-platform.com" ]
5
https://stackoverflow.com/questions/79854613/symfony-objectmapper-fails-on-relational-property
so_79853496
Laravel with Vite: Running dev server in an iFrame
I'm developing a Laravel app that runs inside an iFrame. While everything works fine with production builds ( ), I'm unable to get Vite working in development mode, which makes the development workflow very cumbersome. I am developing for a web-application which has an app-store, where "apps" are actually jus...
I found the solution myself! To get HMR working I had to tunnel both the Laravel server and the Vite dev server through ngrok. So I added a to my file: Next I configured ngrok to handle two tunnels, : I then updated : This way everything works!
[ "Access to script at 'http://[::1]:5173/@vite/client' from origin 'https://<ngrok-url>.eu.ngrok.io' has been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space. GET http://[::1]:5173/@vite/client net::ERR_FAILED Access to script at 'http://[::1]:5173/resources...
php
9.12
stackoverflow
[ "php", "laravel", "iframe", "vite", "inertiajs" ]
5
https://stackoverflow.com/questions/79853496/laravel-with-vite-running-dev-server-in-an-iframe
so_79853026
How to fix Livewire ComponentNotFoundException on wire:click events?
I have a Livewire component where works correctly and displays user name, but triggers a . The error message shows: This is my livewire component class.. This is my component blade... An error was.. This is my error log I can confirm that my classes and filenames are all correct. What is the reason for that? Please gui...
is an internal method and you're overriding it. Simply choose a different name for it.
[ "class UserDropdown extends Component { public string $name; public function getName() { $this->name = Auth::user()->first_name . ' ' . Auth::user()->last_name; return $this->name; } /** * Log the current user out of the application. */ public function logout() { Log::info('Logout function called succes...
php
8
stackoverflow
[ "php", "laravel", "laravel-livewire", "laravel-livewire-wireclick" ]
8
https://stackoverflow.com/questions/79853026/how-to-fix-livewire-componentnotfoundexception-on-wireclick-events
so_79834118
Why does PHP setlocale not seem to accept a BCP 47 script subtag?
If I run the following code on a Linux server I get the output It seems that although the system is claiming the locale 'zh_Hant_TW' is available, when I try and use it with it doesn't work, with returning . Yet when I try 'zh_TW' it does work. Why is this? I get similar results when I try other locales containing scri...
The function and class use two entirely different libraries. Just because one supports a locale, does not mean the other does. PHP's is just a wrapper for the C language's function. Here is a list of supported locales on Windows and Linux . In general, only uses some (a subset) of the languages, countries, and scripts ...
[]
php
7.88
stackoverflow
[ "php", "locale", "intl", "setlocale" ]
11
https://stackoverflow.com/questions/79834118/why-does-php-setlocale-not-seem-to-accept-a-bcp-47-script-subtag
so_79833175
Why does the_field function of ACF plugin return an empty value?
I know that there are similar questions to my question like this one: Insert php variable in a href But my problem does not solve with them! I am using "acf plugin" for adding some codes to my wordpress site. Here is the php code that I used in "code-snippet" plugin: I used the function of the acf p...
is the same as , so you should use , and you also should escape the value before using it:
[ "function add_after($content) { if( get_field('article-file') ) { $downloadLink = the_field('article-file'); $aftercontent = '<p class="fontBold">می‌توانید فایل مرتبط با مطالب این صفحه را از طریق لینک زیر دانلود کنید:</p>' . '<a href="' . $downloadLink . '">دانلود فایل</a&gt...
wordpress
8.12
stackoverflow
[ "php", "wordpress", "advanced-custom-fields" ]
9
https://stackoverflow.com/questions/79833175/why-does-the-field-function-of-acf-plugin-return-an-empty-value
so_79829197
Why do some web browsers incorrectly display currencies produced by NumberFormatter
Why some older web browsers (not all) incorrectly display currency symbols when symbols are produced by php NumberFormatter() but display correct symbol when given as html entity. Since correct symbol is displayed via HTML entity code it means that browser has the font to display the currency symbol correctly. For exam...
There are actually two Yen characters defined in Unicode: YEN SIGN (U+00A5) FULLWIDTH YEN SIGN (U+FFE5) uses the second one, as shown by this test: Outputs ( demo ). If no font with that character is available, then it will not show correctly (unless the browser is smart enough to substitute it with the usual Yen chara...
[ "$locale = 'ja-JP'; $currency = 'JPY'; $formatter = new NumberFormatter($locale."@currency=$currency", NumberFormatter::CURRENCY); header("Content-Type: text/html; charset=UTF-8;"); print htmlspecialchars($formatter->formatCurrency('90023.12', $currency)); Output: *90,023 //Incorrect output, ...
php
9.5
stackoverflow
[ "php", "browser", "character-encoding", "numberformatter" ]
8
https://stackoverflow.com/questions/79829197/why-do-some-web-browsers-incorrectly-display-currencies-produced-by-numberformat
so_79828493
Problem Searching Using Blind Index in Laravel
I am developing an application that contains sensitive data, and I want this data to be encrypted while still being searchable through the application code. I found a solution using the CipherSweet library. The encryption and data display are working correctly, but the search is not. The or chained queries are not work...
CipherSweet blind indexes are designed for exact-match search and do not support LIKE queries or wildcards (%), - wildcard with is what causes fail.
[ "class User extends Authenticatable implements CipherSweetEncrypted { use HasFactory, Notifiable , UsesCipherSweet; protected $fillable = [ 'name', 'email', 'password', ]; public static function configureCipherSweet(EncryptedRow $encryptedRow): void { $encryptedRow // Encrypt the email field ->addField('email') ...
php
9.25
stackoverflow
[ "php", "laravel", "search", "eloquent" ]
6
https://stackoverflow.com/questions/79828493/problem-searching-using-blind-index-in-laravel
so_79827253
Problem with cron setting in Laravel 12 that is not working
I have a Laravel 12.39 project (on PHP 8.3) on a shared hosting with cPanel access, and in the cron section, I have the following setting to run artisan schedule:run, but it isn't working. This was an upgrade from the Laravel 10 project, where the server crons were the same and worked. In my class, I have the following...
In laravel 12, Kernel.php is not used anymore You need to move your code to and the code will look like this in the console.php To check your schedule list, run this command You're supposed to see your cron job and when it will be run next time
[ "<?php namespace App\\Console; use Illuminate\\Console\\Scheduling\\Schedule; use Illuminate\\Foundation\\Console\\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * Define the application's command schedule. */ protected function schedule(Schedule $schedule): void { // Continuous // Queue $sche...
shell_scripting
9.62
stackoverflow
[ "php", "laravel", "cron", "scheduled-tasks", "cpanel" ]
9
https://stackoverflow.com/questions/79827253/problem-with-cron-setting-in-laravel-12-that-is-not-working
so_79826535
`docker-php-ext-install opcache` works with PHP 8.4 but not PHP 8.5
I can build an image with this that is based on a lightweight Docker image that use Alpine: But I can’t build an image after upgrading to PHP 8.5 — it should be noted that this 8.5 image was released only 16 hours ago: It fails with this error: How to avoid this error? Do I have to wait for an update from ? I tried to ...
As documented in the PHP 8.5 changelog , since PHP 8.5 the Opcache extension now always ships with PHP (non-optional). So you don't need to install it any longer. Opcache: Make OPcache non-optional (Arnaud, timwolla) Using or INI directives will emit a warning. If you're looking for the backward incompatible changes of...
[ "RUN /bin/sh -c 'if php -m | grep -qi "$1$"; then \\ printf "%s already installed\\n" "$1"; \\ else docker-php-ext-install -- "$1"; fi' -- \\ opcache" ]
php
10
stackoverflow
[ "php", "docker" ]
26
https://stackoverflow.com/questions/79826535/docker-php-ext-install-opcache-works-with-php-8-4-but-not-php-8-5
so_78933548
How to Map an Array of JSON Objects to an Array of DTOs Using MapRequestPayload
I'm working with Symfony and have an incoming JSON payload that looks like this: I have a Data Transfer Object (DTO) defined like this: My goal is to map the array of JSON objects directly to an array of MyDto objects in my Symfony controller. Here's my current controller method: I'm trying to find a way to map the arr...
Since Symfony 7.1, there is a new argument on attribute which allows you to type hint your controller argument with , and specify the DTOs you expect : cf. https://github.com/symfony/symfony/commit/3f721434062045c1bad7849d1b412d07aa2b98e4
[ "[ { "number": 1, "description": "Test 1" }, { "number": 2, "description": "Test 2" }, { "number": 3, "description": "Test 3" } ]", "<?php class MyDto { public function __constructor( public readonly int $number, public r...
php
10.38
stackoverflow
[ "php", "symfony" ]
15
https://stackoverflow.com/questions/78933548/how-to-map-an-array-of-json-objects-to-an-array-of-dtos-using-maprequestpayload
so_78931003
PHP and Java functions returning different dates when calculating 6 months ahead
I have the following code to calculate what day it will be in 6 months from today. in Java, it returns "2025-02-28" in PHP, it returns "2025-03-02" Why are they different? Can anyone explain it? Thanks!
tl;dr See this code run at Ideone.com . 2025-02-28 Avoid legacy date-time classes You are using terribly flawed date-time classes that are now legacy. They were supplanted years ago by the modern java.time classes defined in JSR 310. For a date-only value, use . Specify six months with class. Add. Explain difference fr...
[ "// PHP code $currentDate = date_create_from_format('Y-m-d', '2024-08-30'); $sixMonthsLaterDate = $currentDate->modify('+6 month'); $sixMonthsLaterDateString = date_format($sixMonthsLaterDate, 'Y-m-d'); echo "sixMonthsLaterDateString: $sixMonthsLaterDateString"; // returns 2025-03-02", "LocalDate.par...
php
9.38
stackoverflow
[ "java", "php", "date", "java-calendar" ]
7
https://stackoverflow.com/questions/78931003/php-and-java-functions-returning-different-dates-when-calculating-6-months-ahead
so_78685410
Symfony + doctrine: Can only configure "xml", "yml", "php", "staticphp" or "attribute" through the DoctrineBundle
upgrading symfony from 6 to 7 getting this doctrine error here is my doctrine.yaml file:
The mapping type in the orm configuration has been deprecated in version 6.4. You probably should move to attributes. Rector can help you with that.
[]
php
6.38
stackoverflow
[ "php", "symfony", "doctrine-orm" ]
7
https://stackoverflow.com/questions/78685410/symfony-doctrine-can-only-configure-xml-yml-php-staticphp-or-attr
so_78408559
PHP 8.3 Typed Class Constants - Closures
This article https://php.watch/versions/8.3/typed-constants#supported_types affirms that PHP 8.3 allows us to declare typed constants of Closure type. But I could not find any reference on how to do it. Is it a mistake, or is there the possibility to have closures as constants? How can it be done? I tried to guess the ...
The keyword only supports limited expressions, but the function supports arbitrary expressons, so you can use it to define a constant first and then assign it to a class constant. This doesn't make much sense, I agree with the article just pointing out that Closure is an allowed type. BTW if you try to invoke the const...
[ "class ClassWithTypedConstants { public const int INTEGER = 1; public const int|string INTEGER_OR_STRING = 1; public const \\Closure CLOSURE = () => {}; }", "define('CL', function () { echo "hello\\n"; }); class Foo { public const \\Closure CL = CL; }" ]
php
9.75
stackoverflow
[ "php", "syntax", "constants" ]
10
https://stackoverflow.com/questions/78408559/php-8-3-typed-class-constants-closures
so_73561847
What is the pool of characters used in a BCRYPT hash
I was looking for answers on BCRYPT specific resources but found the anwser within PHP's documentation for . I have an issue whereby I need to do some REGEX to clean a BCRYPT hash (generated by PHP function using ). I want to be able to know the characters that could theoretically appear in the BCRYPT hash so that REGE...
I found the answer on the PHP Crypt Function page: CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt ...
[]
php
7.38
stackoverflow
[ "php", "bcrypt" ]
7
https://stackoverflow.com/questions/73561847/what-is-the-pool-of-characters-used-in-a-bcrypt-hash
so_72452847
Where is the key to use for Android FCM push notification?
I installed firebase, and if I send manually push notification through firebase console, my app receives it. I'm trying to send a notification to FCM using a php script. The problem is I don't know what key I'm supposed to use ? If I use the one in firebase console, I got this 401 error: "Invalid Key" If I us...
Try to enable Cloud Messaging API (Legacy) in Firebase Console project settings.
[ "$server_key = "" $token = "" $title = "" $body = "" $curl = curl_init(); $authKey = "key=" . $server_key; $registration_ids = $token; curl_setopt_array($curl, array( CURLOPT_URL => "https://fcm.googleapis.com/fcm/send", CURLOPT_RETURNTRANSFER => tru...
php
7
stackoverflow
[ "php", "android", "firebase", "firebase-cloud-messaging" ]
4
https://stackoverflow.com/questions/72452847/where-is-the-key-to-use-for-android-fcm-push-notification
so_71695459
VichUploaderBundle in Symfony 6
I hope you can help me because i'm searching and i'm lost :( I'm trying to upload image in my symfony 6 project with VichUploaderBundle. I used the doc : https://github.com/dustin10/VichUploaderBundle/blob/master/docs/usage.md#step-1-configure-an-upload-mapping But i have this error : The class "App\Entity\Client&...
Assuming you are using Php 8+ configure the bundle to use attributes instead of annotations ref docs Edit 21 Nov 2022: As of v2 of the bundle, is the default value.
[ "<?php namespace App\\Entity; use Doctrine\\ORM\\Mapping as ORM; use App\\Repository\\ClientRepository; use Doctrine\\Common\\Collections\\Collection; use Symfony\\Component\\HttpFoundation\\File\\File; use Doctrine\\Common\\Collections\\ArrayCollection; use Vich\\UploaderBundle\\Mapping\\Annotation as Vich; #[O...
php
10.5
stackoverflow
[ "php", "symfony", "vichuploaderbundle" ]
22
https://stackoverflow.com/questions/71695459/vichuploaderbundle-in-symfony-6
so_70932661
Make all error status codes return a single custom view
By default , Laravel looks for error views under , returning the corresponding view for the relevant status code, eg. 404 or 403. Instead of creating all these views manually I want to use my own custom view for all error codes, with the actual error code and message shown dynamically in the view using and any other he...
In the default exception handler , a method called determines the view to return. Simply override it in your class with your desired logic. You're returning a standard view path, dot-separated if you are using directories.
[ "use Symfony\\Component\\HttpKernel\\Exception\\HttpExceptionInterface; protected function getHttpExceptionView($e) { if ($e->getStatusCode() === 409) { return "exceptions.special"; } return "exceptions.default"; }" ]
php
9
stackoverflow
[ "php", "laravel", "error-handling", "laravel-8", "http-status-codes" ]
8
https://stackoverflow.com/questions/70932661/make-all-error-status-codes-return-a-single-custom-view
so_64626453
in my morris.js graph the date on the X axis is adding the number 19 before the month-day date
this is the sql to get the data from data base and puts the data in an array. also it splits the date from year-month-day format to month-day format this is the script that is used to create the graph.
If you want to display the date in the x-axis without the year, you need to format it in javascript instead of in php. When you get a date like "11-05" from php, morris parses that back into a javascript date object, and it doesn't have the year part, so it ends up parsing the date as "May, 1911". L...
[ "$sql = "SELECT * FROM Time WHERE Event_ID='$event' AND Student_ID='$runner'"; $result=$conn->query($sql); while($row = $result->fetch_assoc()) { $date[]= date('m-d',strtotime($row['Date'])); $time[]=$row['time']; $count=$count+1; }", "new Morris.Line({ // ID of the element in which to draw the ch...
php
8.88
stackoverflow
[ "javascript", "php", "html", "jquery", "morris.js" ]
3
https://stackoverflow.com/questions/64626453/in-my-morris-js-graph-the-date-on-the-x-axis-is-adding-the-number-19-before-the
so_64147093
laravel recursion display referred users by level/depth
So I'm working with affiliate and doing fine with registration and saving who referred to a user, now I'm struggling in showing those users with referrals by Level. Level is not save in the database, I'm thinking of it as incrementing in the logic area? users table structure so the output I want should be like this: I ...
If MySQL 8 (very advised with hierarchical data like yours), you can do this with a recursive CTE : Now you have virtual table containing the column for all your users and you can query it DBFiddle GOing further... Make a view out of your CTE Now it's easy to get all your users levels (no need to have the CTE statement...
[ "public function sponsor() { return $this->belongsTo('App\\User', 'sponsor_id'); }", "public function referrals() { return $this->hasMany('App\\User', 'sponsor_id'); }" ]
sql
9.75
stackoverflow
[ "php", "mysql", "laravel" ]
10
https://stackoverflow.com/questions/64147093/laravel-recursion-display-referred-users-by-level-depth
so_63679593
Laravel Dusk: Facebook\WebDriver\Exception\UnknownErrorException: unknown error: net::ERR_CONNECTION_REFUSED
Running php artisan dusk get the error: Versions: OS: Windows 10 v1903 build 18362.1016 Chrome: 85.0.4183.83 Laravel: v6.18.37 Dusk: v5.11.0 Phpunit: v8.5.8 Tried: Disable firewall Set test website to use localhost (was myapp.local) Can access all pages using Chrome browser Check that vendor/laravel/dusk/bin/chromedriv...
I faced the same issue and for me what worked was setting the parameter in the .env file as: As that was the same port on which my would also serve the website i.e.
[ "{ value: { error: "unknown command", message: "unknown command: unknown command: ", stacktrace: "Backtrace: Ordinal0 [0x0037D383+3134339] Ordinal0 [0x0026A171+2007409] Ordinal0 [0x0010AEE8+569064] Ordinal0 [0x000AD12C+184620] Ordinal0 [0x000ACF0A+184074] Ordinal0 [0x00081FD7+8151] Ordinal0...
php
10.5
stackoverflow
[ "php", "laravel", "google-chrome", "automated-tests", "laravel-6" ]
33
https://stackoverflow.com/questions/63679593/laravel-dusk-facebook-webdriver-exception-unknownerrorexception-unknown-error
so_63675932
what does it mean by "typed objects"?
in the documentation of laravel for container service through this link: https://laravel.com/docs/7.x/container below the title : "Binding Typed Variadics" you will find this : Occasionally you may have a class that receives an array of typed objects using a variadic constructor argument. so what is typed obj...
Since PHP is an interpreted language you have a dynamic type system. That means, that for example a sinlge variable can hold values of multiple types: Now the question becomes where the "typed objects" fit in. In PHP Version 5 type declarations got introduced, because the dynamic type system imposes some prob...
[ "class Firewall { protected $logger; protected $filters; public function __construct(Logger $logger, Filter ...$filters) { $this->logger = $logger; $this->filters = $filters; } }", "$foo = "Now I'm a string"; $foo = 42; // And now I'm a number", "function doSomething($a, $b) { // imagine costly ...
php
9.12
stackoverflow
[ "php", "laravel", "object", "containers", "typed" ]
5
https://stackoverflow.com/questions/63675932/what-does-it-mean-by-typed-objects
so_62667344
PHP Closures - Getting class name of closure scope origin
Case I am playing around on a laravel project to see if i can use closures for my implementation of a sorting interface, and i noticed that when i my closure, it also shows the class in which the closure was created as a property. Minimised Code The result of the inside : Question From the result of the it shows that t...
You may use Reflection API on your closure which is a much cleaner way than returns a instance based on the class you need to find and finishes the job.
[ "// in my Order model class, i have a function that will return a closure public static function defaultSortFunction(){ $sortColumn = property_exists(self::class,'defaultSortingColumn') ? self::$defaultSortingColumn : 'created_at'; return function($p,$n)use($sortColumn){ return $p->$sortColumn <=> $n->$...
php
10.12
stackoverflow
[ "php", "laravel", "closures" ]
13
https://stackoverflow.com/questions/62667344/php-closures-getting-class-name-of-closure-scope-origin
so_61534306
strtotime('-1 month') returning wrong date if month have 31 days
I'm trying make a function to return the exact date of previous months. That is a example of my code: The problem is in that represents February, the output is 2020-03-01 instead 2020-02-29 and I suppose that problem will happen in months who have 30 days when present date have 31 days. What is the best way to resolve ...
As you can see working with the end of the month can be problematic because of how PHP works with dates. Your best bet is to go back to the beginning of the month, do your date math (i.e. go backwards in time), and then go to the date you want. That way you can check to see if the current day is greater than the number...
[ "// Dates in TimeStamp $ts_now = strtotime('now'); $ts_month1 = strtotime(\"-1 month\", $ts_now); $ts_month2 = strtotime(\"-2 month\", $ts_now); $ts_month3 = strtotime(\"-3 month\", $ts_now); // Dates Formated $date_now = date('Y-m-d', $ts_now); $date_month1 = date('Y-m-d', $ts_month1); $date_month2 = date('Y-m-d',...
php
9.5
stackoverflow
[ "php", "date", "datetime" ]
8
https://stackoverflow.com/questions/61534306/strtotime-1-month-returning-wrong-date-if-month-have-31-days
so_60957876
passing a JavaScript array to PHP file returns empty array
I'm trying to pass a javascript array to PHP file like this: Code in JS file: And inside the PHP file: But each time I get an empty array! How can I fix this? Update : PHP Javascript UPDATE 2: JS PHP Still I get
Try print your response with print_r($_POST) You will see you don't send {directories: directories} in your request's body and in your php you try get data: $_POST['directories'] so you get a response with server error (500 status) Updated: And it's better if you send just one request and send all data with that and in...
[ "let directories =JSON.stringify([\"John\", \"Sara\", \"Max\"]); $.post('../test.php', {directories: directories});", "$directories = json_decode($_POST['directories']);", "<?php function getDirContents($directories, &$results = array()){ $length = count($directories); for ($i = 0; $i < $length; $i++)...
php
9
stackoverflow
[ "javascript", "php" ]
4
https://stackoverflow.com/questions/60957876/passing-a-javascript-array-to-php-file-returns-empty-array
so_60468419
In Laravel does artisan config:cache actually cache the config as specified in the cache.php settings?
I have set up Laravel to use Redis as the cache. I can verify that it is working when I use the then inspecting Redis via the CLI to see that the key already been created. My question is, after caching the Laravel config with should I expect to see some entries in Redis since I've set up Laravel to use Redis as the cac...
When you use , a static PHP file will be generated on that returns all configs as an array. So the answer to should I expect to see some entries in redis since I've set up Laravel to use redis as the cache? is NO, the Laravel won't use your cache driver to cache configs.
[]
php
7.62
stackoverflow
[ "php", "laravel", "caching" ]
9
https://stackoverflow.com/questions/60468419/in-laravel-does-artisan-configcache-actually-cache-the-config-as-specified-in-t
so_52582130
Getting N-th day of month using DateTime()
I need to get date of 10th day of current month. This way is not working: Results: Warning: DateTime::modify(): Failed to parse time string (tenth day of this month ) at position 10 (o): The timezone could not be found in the database in [...][...] on line 3 Of cource, I can use but I need to make it with DateTime() ob...
I found correct way: Result on 2018-09-30:
[ "<?php $date_start = new DateTime(); $date_start->modify('tenth day of this month'); echo $date_start->format('Y-m-d H:i:s'), \"\\n\"; ?>", "<?php $date_start = new DateTime(); $date_start->modify('first day of this month'); $date_start->modify('+9 days'); echo $date_start->format('Y-m-d')...
php
7.88
stackoverflow
[ "php", "datetime", "strtotime" ]
7
https://stackoverflow.com/questions/52582130/getting-n-th-day-of-month-using-datetime
so_52581975
Does null coalescing operator call a function twice?
The null coalescing operator ( ) returns its first operand if it exists and is not NULL, and otherwise returns its second operand. If the first operand is a function or method call, does the operator call the function call twice? As an example, say the function returns a string value or null. So is called once and the ...
It's only called once. This is quite easy to see if you add a side effect to your function, such as printing, e.g.: Demo
[ "$name = get_name() ?? 'no name found';", "<?php function get_name() { print(\"get_name() was called\\n\"); return \"somestring\"; } $name = get_name() ?? 'no name found'; print($name); ?>" ]
php
10
stackoverflow
[ "php", "php-7", "null-coalescing-operator" ]
12
https://stackoverflow.com/questions/52581975/does-null-coalescing-operator-call-a-function-twice
so_52581962
Remove items count from my account orders table in Woocommerce
I need to remove this item count text in my orders table at the my account page, because I don't need it: The text at Gesamtsumme should be changed from: 234,35€ for 1 Artikel to 234,35€ I've tried it with deleting it in the file but I want to do this via my functions.php because this is better I think.
The correct way to make it work for singular and plural item count, for all languages is (where is the untranslated string) : Code goes in function.php file of your active child theme (or active theme). Tested and works.
[ "add_filter('ngettext', 'remove_item_count_from_my_account_orders', 105, 3 ); function remove_item_count_from_my_account_orders( $translated, $text, $domain ) { switch ( $text ) { case '%1$s for %2$s item' : $translated = '%1$s'; break; case '%1$s for %2$s items' : $translated = '%1$s'; break; } return $translated;...
wordpress
9
stackoverflow
[ "php", "wordpress", "woocommerce", "account", "orders" ]
8
https://stackoverflow.com/questions/52581962/remove-items-count-from-my-account-orders-table-in-woocommerce
so_52122275
Add a product review with ratings programmatically in Woocommerce
The title says it all. I know the reviews are the native comments post type in Wordpress. I have included the code to add a comment. The problem is however I am unclear how to give the comment a rating and how to tie it to a particular product. When I use the comment_post_ID it does not seem to be assigning the comment...
With the key is where your comment will be shown, so desired product ID Then you can use dedicated WordPress function to add a rating, like: So your code will be like (where is the targeted product Id for this review): Tested and works as intended. The author email and the user ID need to be some existing ones.
[ "$time = current_time('mysql'); $data = array( 'comment_post_ID' =&gt; 1, 'comment_author' =&gt; 'admin', 'comment_author_email' =&gt; '<REDACTED_EMAIL>', 'comment_author_url' =&gt; 'http://', 'comment_content' =&gt; 'content here', 'comment_type' =&gt; '', 'comment_parent' =&gt; 0, 'user_id' =&gt; 1, 'comment_auth...
wordpress
10.5
stackoverflow
[ "php", "wordpress", "woocommerce", "comments", "rating" ]
16
https://stackoverflow.com/questions/52122275/add-a-product-review-with-ratings-programmatically-in-woocommerce
so_51623262
Move product title above product image on Woocommerce archive pages
I am trying to move the product title above the product image on the product archive page. I have managed to figure out how to move the information, but the price is moving above the image aswell. I want only the product title to be above the product image. The price should remain below, with the add to cart button etc...
Instead try the following, where you will set the product thumbnail just after the product title: Code goes in function.php file of your active child theme (or active theme). Tested and works. It should work for you too.
[ "remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 ); add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );", "remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product...
wordpress
9.38
stackoverflow
[ "php", "wordpress", "woocommerce", "product", "hook-woocommerce" ]
7
https://stackoverflow.com/questions/51623262/move-product-title-above-product-image-on-woocommerce-archive-pages
so_51621959
Get user total purchased items count in Woocmmmerce
I'm trying to figure out a function which get current user total number of purchased items (not total sum but items) across as all placed orders. So far I have found this (which doesn't work) - but again this function should get total sum and not items. Been trying to edit it to work but no success so far. Any ideas?
Updated (Taking in account the item quantity) The following very lightweight function will get the total purchased items count by a customer: Code goes in function.php file of your active child theme (or active theme). Tested and works. USAGE Example 1) Display the current user total purchased items count: 2) Display t...
[ "public function get_customer_total_order() { $customer_orders = get_posts( array( 'numberposts' =&gt; - 1, 'meta_key' =&gt; '_customer_user', 'meta_value' =&gt; get_current_user_id(), 'post_type' =&gt; array( 'shop_order' ), 'post_status' =&gt; array( 'wc-completed' ) ) ); $total = 0; foreach ( $customer_orders as...
wordpress
9.38
stackoverflow
[ "php", "sql", "wordpress", "woocommerce", "orders" ]
7
https://stackoverflow.com/questions/51621959/get-user-total-purchased-items-count-in-woocmmmerce
so_51119299
Laravel 5.6 Trying to get property of non-object
When i try echo the value i receive an exeception. I check the collection with dd() and is not null. My Models: Cliente: OrdemServico: OrdemServicoController: Part View Home: When i I receive: dd() return But when i try echo the value, i receive a execpetion. dd() of $ordem. https://gist.github.com/vgoncalves13/8140a7a...
Perhaps your relationship should be called assuming a order only belongs to one ... and you should pass the third argument which is the ... you can avoid this type of error by using english (since laravel would search for customer_id and order_id) Try the following code namespace App; use Illuminate\Database\Eloquent\M...
[ "&lt;?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class Cliente extends Model { protected $table = 'clientes'; public function ordens() { return $this-&gt;hasMany('App\\OrdemServico','cliente_id'); } }", "&lt;?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class OrdemServico exten...
php
9.25
stackoverflow
[ "php", "laravel", "laravel-5", "foreach", "eager-loading" ]
6
https://stackoverflow.com/questions/51119299/laravel-5-6-trying-to-get-property-of-non-object
so_50633080
How to add a &quot;Review title&quot; field on WooCommerce reviews form?
I want to add a custom field to my reviews form on WooCommerce just like this image: And then how to get the output of that title just like that: I just know how to create a new field on the single-product-reviews.php file by adding that code: But, how can I save this on the database and how can I output this title abo...
It's too good to find a solution myself, this my answer of what I'm looking for, maybe can help you! 1) Go to your functions.php on your parent or child theme then paste that code below to add the custom field "Review title" on reviews comment form: 2) Save that field value on wp_commentmeta table on the database by ad...
[ "$comment_form['comment_field'] .= '&lt;p class=\"comment-form-title\"&gt;&lt;label for=\"title\"&gt;' . esc_html__( 'Review title', 'woocommerce' ) . '&amp;nbsp;&lt;span class=\"required\"&gt;*&lt;/span&gt;&lt;/label&gt;&lt;input id=\"title\" name=\"title\" type=\"text\" aria-required=\"true\" required&gt;&lt;/inp...
wordpress
10.5
stackoverflow
[ "php", "wordpress", "woocommerce" ]
17
https://stackoverflow.com/questions/50633080/how-to-add-a-review-title-field-on-woocommerce-reviews-form
so_50632632
How should I set the download name of a pdf with fpdf?
I am trying to set a name for a pdf file I generated with FPDF. However for some reason the browser changes some characters. I am sending this: Yet when I save my pdf it changes some characters and I and the download name becomes: 'Overview_ 2017_2018'. I am using UTF-8 encoding on my php file. FPDF-documentation: http...
You are using the special characters and in your filename in your code. Because of this is filtering your outputs filename. For example: Tip: You may add in your name if file is not saving as pdf file.
[ "$pdfTitle = 'Overview: 2017/2018' $pdf-&gt;Output( 'D', $pdfTitle, true );" ]
php
8.5
stackoverflow
[ "php", "character-encoding", "fpdf" ]
4
https://stackoverflow.com/questions/50632632/how-should-i-set-the-download-name-of-a-pdf-with-fpdf
so_50632310
php artisan serve can&#39;t find the autoload.php
SOLUTION: was actually giving me an error that i overlooked. I had the wrong version of php. It requires phpv7.1.3 or higher. If you don't have it it doesn't work. Ran into one other problem: i had a system environment variable that is pointing to an old version of php Also laravel requires openssl extension and mbstri...
When running laravel new project_name. It outputted the text php 7.1.3 or higher needs to be installed. Current version 5.6 does not match requirements. And it aborts without plainly giving you an error. Be sure to download php version 7.1.3 or higher. Also check if you have environment variables for earlier versions o...
[]
php
6.88
stackoverflow
[ "php", "laravel", "laravel-artisan" ]
3
https://stackoverflow.com/questions/50632310/php-artisan-serve-cant-find-the-autoload-php
so_51113506
NodeJS map Dtos to TypeORM Entities
I have a REST API backend running the framework, using typeORM as ORM for my entities. Coming from a background, I am very used to have my Dtos mapped to the database entities. Is there a similar approach with typeORM? I have seen the automapper-ts library, but those magic strings in the map declarations look kind of s...
You can use class-transformer library. You can use it with class-validator to cast and validate POST parameters. Example: and here are from to avoid additional fields. , , , , are from . is for Swagger documentation And then
[ "@Exclude() class SkillNewDto { @Expose() @ApiModelProperty({ required: true }) @IsString() @MaxLength(60) name: string; @Expose() @ApiModelProperty({ required: true, type: Number, isArray: true, }) @IsArray() @IsInt({ each: true }) @IsOptional() categories: number[]; }", "const skillDto = plainToClass(SkillNewDt...
typescript
10.5
stackoverflow
[ "node.js", "dto", "nestjs", "typeorm", "class-transformer" ]
17
https://stackoverflow.com/questions/51113506/nodejs-map-dtos-to-typeorm-entities
so_51056158
NestJS Create Base CRUD Service
I am writing my first REST API with nestjs. I have several entities for which I have to define basic CRUD operations. I was wondering if there is a way to create a base crud service that I can use in order not to repeat the same code for all entities. In this base-crud service I would have the four CRUD methods that ca...
Create a base-crud service as follows : And than have the individual services extend that class : Et-voilà now you have insert, delete, update etc already taken care of..and this for all services that extend the class. Following this logic you can easily create a .
[ "export class BaseCrudService&lt;Entity extends BaseEntity&gt; { constructor( public repository: Repository&lt;Entity&gt;, ) { } async insertAsync(entity: Entity): Promise&lt;InsertResult&gt; { return this.repository.insert(entity); } ... }", "@Injectable() export class UserService extends BaseCrudService&lt;User...
typescript
10.5
stackoverflow
[ "nestjs" ]
28
https://stackoverflow.com/questions/51056158/nestjs-create-base-crud-service
so_51045980
how to serve assets from Nest.js and add middleware to detect image request
I am trying to serve image from Nest.js server and add middleware to track all request but the only way I could make it work was with express How can I implement it with using the controller or middleware?
The nestjs doc tells you, how to serve static files. In short, here is how you do it: Specify root directory of your assets in you main.ts Use the @Res annotation to be able to use the sendFile method of express framework This solution assumes that your nestjs installation uses express under the hood. Sources: https://...
[ "import { NestFactory } from '@nestjs/core'; import * as bodyParser from \"body-parser\"; import {AppModule} from \"./app.module\"; import * as path from \"path\"; import * as express from 'express'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(bodyParser.json({limit: '50mb'...
typescript
10.5
stackoverflow
[ "node.js", "express", "nestjs" ]
35
https://stackoverflow.com/questions/51045980/how-to-serve-assets-from-nest-js-and-add-middleware-to-detect-image-request
so_50977202
NestJS JwtStrategy use configService to pass secret key
I have the JwtStrategy class from docs example ( https://docs.nestjs.com/techniques/authentication ): When I am trying access before calling super() I get an error. But I still want to use configService to get secret key. I know that I can use env var to do that, but service approach is more clearer solution, in my opi...
Just remove , see here: It will work since has been passed as a parameter.
[ "@Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private readonly authService: AuthService, private readonly configService: ConfigService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: this.configService.getSecretKey, }); } // ... }" ]
typescript
8.5
stackoverflow
[ "typescript", "nestjs", "passport-jwt" ]
33
https://stackoverflow.com/questions/50977202/nestjs-jwtstrategy-use-configservice-to-pass-secret-key
so_50935416
Role verification in nestJs framework using passport-jwt
I implemented authentication strategy basing on that article: https://docs.nestjs.com/techniques/authentication . But I would like to expand that JwtStrategy on checking roles. It would be easiest to just add checks for oles in as there is already taken user basing on JWT payload. But I don't know how to pass additiona...
You will need to have another guard to make a role verification. You can get an example of implementation in NestJS docs ( https://docs.nestjs.com/guards ), in the "Role-based authentication" section.
[ "async validate(payload: JwtPayload, done: Function, role: string) { const user = await this.authService.validateUser(payload); if (!user || user.role !== role) { return done(new UnauthorizedException(), false); } done(null, user); }" ]
typescript
10
stackoverflow
[ "typescript", "passport.js", "nestjs" ]
30
https://stackoverflow.com/questions/50935416/role-verification-in-nestjs-framework-using-passport-jwt
so_50928311
How to use in-memory database with TypeORM in Nest
I have a Nest server that other services depends on. In order to simplify testing of these other services, I would like to spin up a version of the Nest server that does not use a real database. Instead, it should use an in-memory db, like mongo-unit . My idea would be to have a production main module, and a test main ...
It should be possible using async dynamic modules . Alternatively, spinning up the mongo-unit in the test and configuring the application to connect to that db works even better, since the test then has control over the db. I'm using this latter approach. (Unfortunately, there are some issues with it.)
[ "// app.module.ts import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ ... TypeOrmModule.forRoot({ type: 'mongodb', host: 'localhost', port: 27017, database: 'production', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }), ... ], }) expo...
typescript
10.38
stackoverflow
[ "typescript", "typeorm", "nestjs" ]
15
https://stackoverflow.com/questions/50928311/how-to-use-in-memory-database-with-typeorm-in-nest
so_50913705
Nestjs/swagger: Complex Objects
I was wondering if there's a way to support complex objects for Nestjs/swagger. I just finished the migration and I am now working on the swagger documentation. A lot of my requests return complex objects and I'm wondering if there's an easier way. Example: Becomes: If I do this: I get this in swagger:
UPDATE 04/2020 : now has been changed to In the last , I used "Lazy Evaluated Function" syntax. This is to prevent Circular Dependency problem. Thought I'd add it in there. The takes in an option object where you can specify the if it's a complex object.
[ "class Foobar{ prop1: { subprop1: { subsub1: string; }; }; }", "class SubSub{ @ApiModelProperty() subsub1: string; } class SubProp{ @ApiModelProperty() subporp1: SubSub; } class Foobar { @ApiModelProperty() prop1: SubProp; }", "class Foobar{ @ApiModelProperty() prop1: { subprop1: { subsub1: string; }; }; }", ...
typescript
10.5
stackoverflow
[ "swagger", "nestjs" ]
93
https://stackoverflow.com/questions/50913705/nestjs-swagger-complex-objects
so_50864001
How to handle mongoose error with nestjs
I followed the example from https://docs.nestjs.com/techniques/mongodb The issue is when there is a mongoose validation error (e.g i have a schema with a required field and it isn't provided): From games.service.ts: The save() function returns a Promise. Now i have this in the game.controller.ts What is the best way to...
First, you forgot to add in your create method inside the controller. This is a common, very misleading mistake I made a thousand of times and took me hours to debug. To catch the exception: You could try to catch MongoError using . For my projects I'm doing the following: You can then just use it like this in your con...
[ "async create(createGameDto: CreateGameDto): Promise&lt;IGame&gt; { const createdGame = new this.gameModel(createGameDto); return await createdGame.save(); }", "@Post() async create(@Body() createGameDto: CreateGameDto) { this.gamesService.create(createGameDto); }", "import { ArgumentsHost, Catch, ConflictExcep...
typescript
10.5
stackoverflow
[ "typescript", "nestjs" ]
40
https://stackoverflow.com/questions/50864001/how-to-handle-mongoose-error-with-nestjs
so_50855317
Vscode + NestJs modules infrequently not found
This is really driving me nuts: I created a fresh new NestJs project with the @nestjs/cli command. At the beginning everything was fine. Then after adding a controller via and installing types for jasmine and node, somehow the modules cannot be found anymore. I recreated a new project over and over and always after a t...
Okay, this was a simple, dump configuration mistake: The special thing was that I had a project structure like that: and totally missed that I needed to set the property in tsconfig.json to . After doing so, all modules could be found properly. For those still having problems, you may also want to take a look at the pr...
[ "{ \"compilerOptions\": { \"module\": \"commonjs\", \"declaration\": false, \"noImplicitAny\": false, \"removeComments\": true, \"noLib\": false, \"allowSyntheticDefaultImports\": true, \"emitDecoratorMetadata\": true, \"experimentalDecorators\": true, \"target\": \"es6\", \"sourceMap\": true, \"allowJs\": true, \"...
typescript
8.25
stackoverflow
[ "node.js", "typescript", "visual-studio-code", "nestjs" ]
2
https://stackoverflow.com/questions/50855317/vscode-nestjs-modules-infrequently-not-found
so_50831216
NestJs - Send Response from Exception Filter
I'm trying to achieve a simple behavior: Whenever an exception is thrown I would like to send the error as a response. My kind of naive code looks like this, but doesn't respond at all: Exception Filter: Module main.ts Is there anything I miss? Thanks in advance :)
This code seems to be working fine for me. Nest version: 5.0.1
[ "import { ExceptionFilter, ArgumentsHost, Catch } from '@nestjs/common'; @Catch() export class AnyExceptionFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { return JSON.stringify( { error: exception, }, null, 4, ); } }", "@Module({ imports: [], controllers: [AppController, TestContr...
typescript
8.62
stackoverflow
[ "exception", "nestjs" ]
13
https://stackoverflow.com/questions/50831216/nestjs-send-response-from-exception-filter
so_50822301
NestJS Cannot resolve dependencies of the UsersModule
NestJS Cannot resolve dependencies of the UsersModule. Error: Error: Nest can't resolve dependencies of the UsersModule (?). Please verify whether [0] argument is available in the current context. app.module.ts: users.module.ts: Problem is this ErrorService, but for instance Database module is used in similar way, and ...
is not properly injected in . It should either be: In the of In the of one module ed by Otherwise, Nest won't be able to resolve it. And adding it to the of doesn't make it globally available, either. I can see three solutions: 1 - Adding to the of . But it doesn't look a proper way, as I think/guess that you will reus...
[ "@Module({ imports: [ ConfigModule, DatabaseModule, GraphQLModule, UsersModule, ], providers: [ ErrorService, ], exports: [ DatabaseModule, ErrorService, ], }) export class AppModule implements NestModule {}", "@Module({ imports: [ DatabaseModule, ErrorService, ], providers: [ UsersService, ...usersProviders, Use...
typescript
10.5
stackoverflow
[ "typescript", "nestjs" ]
32
https://stackoverflow.com/questions/50822301/nestjs-cannot-resolve-dependencies-of-the-usersmodule
so_50808189
Nest can&#39;t resolve dependencies of the PhotoService (?)
I'm starting with Nest.js and I'm getting an error after I create a service: Nest can't resolve dependencies of the PhotoService (?). Please verify whether [0] argument is available in the current context. I'm following the database example: https://docs.nestjs.com/techniques/database Here is my full code: https://gith...
In your remove from providers. Then in , just export :
[ "@Module({ // ...prev code exports: [PhotoService], })" ]
typescript
8.5
stackoverflow
[ "node.js", "typescript", "nestjs" ]
120
https://stackoverflow.com/questions/50808189/nest-cant-resolve-dependencies-of-the-photoservice
so_50654877
TypeError: Class constructor MixinStrategy cannot be invoked without &#39;new&#39;
I was following along with the jwt example like found here https://docs.nestjs.com/techniques/authentication . I copied and pasted the example. After npm installing the necessary bits and bops I got this error which does not occur in the sample which I just copied. Of which I have no idea what it means! Anyone any idea...
The project lacks typings, so they should be additionally installed: This results in src\auth\jwt.strategy.ts (10,6): Call target does not contain any signatures. (2346) error, because wasn't properly typed; return type is . In order to fix this, should be changed to:
[ "TypeError: Class constructor MixinStrategy cannot be invoked without 'new' 8 | export class JwtStrategy extends PassportStrategy(Strategy) { 9 | constructor(private readonly authService: AuthService) { &gt; 10 | super({ 11 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 12 | secretOrKey: 'secretKey', 1...
typescript
9.88
stackoverflow
[ "typescript", "jwt", "passport.js", "nestjs" ]
11
https://stackoverflow.com/questions/50654877/typeerror-class-constructor-mixinstrategy-cannot-be-invoked-without-new
so_49593241
Include Custom Order Status in Woocommerce Orders sales reports
I have a custom order status - In Progress. The code I have for it is below. It works great - but the orders with this custom order status are not being included in the standard Woo Sales Reports or the Woocommerce Status Dashboard Widget. Could someone please help me out and take a look and see how I can add to this s...
You can use the following hooked function, that will add your "custom status" to Orders reports: Tested and works. There is a generated error in your 3rd function related to … Instead you can chnage it this way: It will avoid this small error as is not in the URL of order edit pages (I know is my fault as this was the ...
[ "// 1 New order status AFTER woo 2.2 IN PROGRESS add_action( 'init', 'register_my_new_order_statuses' ); function register_my_new_order_statuses() { register_post_status( 'wc-in-progress', array( 'label' =&gt; _x( 'In Progress', 'Order status', 'woocommerce' ), 'public' =&gt; true, 'exclude_from_search' =&gt; false...
wordpress
10.38
stackoverflow
[ "php", "wordpress", "woocommerce", "report", "orders" ]
15
https://stackoverflow.com/questions/49593241/include-custom-order-status-in-woocommerce-orders-sales-reports
so_49592772
Google reCAPTCHA V2 JavaScript We detected that your site is not verifying reCAPTCHA solutions
Error Message We detected that your site is not verifying reCAPTCHA solutions. This is required for the proper use of reCAPTCHA on your site. Please see our developer site for more information. I created this reCaptcha code, it works well but I don not know how can I validate it, I thought it was validating with the fu...
The function will only provide you with the user response token, which then must be validated with call on google reCAPTCHA server. You could use AJAX request, to validate the token, but these validations should always be done on server side , for security reasons - JavaScript could've always been meddled with by user ...
[ "&lt;!DOCTYPE&gt; &lt;html&gt; &lt;head &gt; &lt;title&gt;&lt;/title&gt; &lt;script src='https://www.google.com/recaptcha/api.js'&gt;&lt;/script&gt; &lt;script type=\"text/javascript\"&gt; function get_action() { var v = grecaptcha.getResponse(); console.log(\"Resp\" + v ); if (v == '') { document.getElementById('c...
php
10.5
stackoverflow
[ "javascript", "php", "ajax", "recaptcha", "invisible-recaptcha" ]
16
https://stackoverflow.com/questions/49592772/google-recaptcha-v2-javascript-we-detected-that-your-site-is-not-verifying-recap
so_40899042
Why is a DateTime object unavailable until I do a no-op?
I'm new to PHP. The following bug(?) took me 891723498 hours to locate in my code. Can someone explain to me what is causing this, and maybe a way to fix it? Right now I'm just leaving the call in. This is a distilled version of my code. There may be other functions than that have the same effect, I don't know. This is...
Ok, based on the comments and links provided, it looks like this is a known (but unprioritized) issue, per http://bugs.php.net/bug.php?id=49382 and Why can&#39;t I access DateTime-&gt;date in PHP&#39;s DateTime class? Is it a bug? The issue appears to be lazy loading of the DateTime class, which isn't apparently correc...
[ "./bin/boris [1] boris&gt; function broken () { [1] *&gt; $timezone = new DateTimeZone(\"America/New_York\"); [1] *&gt; $datetime = new DateTime(\"now\", $timezone); [1] *&gt; return date_parse($datetime-&gt;date); [1] *&gt; } // NULL [2] boris&gt; [2] *&gt; function works () { [2] *&gt; $timezone = new DateTimeZon...
wordpress
9
stackoverflow
[ "php", "wordpress", "datetime" ]
4
https://stackoverflow.com/questions/40899042/why-is-a-datetime-object-unavailable-until-i-do-a-no-op
so_40351479
PHP: &#39;salt&#39; option to password_hash is deprecated
I'm using password hashing for a registration. I need to create a Salt manually and following is the code I have used: When I run this code it gives me an error saying: password_hash(): Use of the 'salt' option to password_hash is deprecated" Any solution for this?
Yes, there's a solution - don't use the 'salt' option. You don't need to salt manually, PHP does that automatically for you. It's not an option to add salt, but to replace the would-be-generated one, and under no circumstances would you be able to provide a better salt - that's why it's deprecated.
[ "$options = [ 'cost' =&gt; 11, 'salt' =&gt; mcrypt_create_iv(22, MCRYPT_DEV_URANDOM) ]; $<REDACTED_SECRET>( $this-&gt;input-&gt;post(\"confirm_password\"), PASSWORD_BCRYPT, $options );" ]
php
9
stackoverflow
[ "php", "php-password-hash" ]
8
https://stackoverflow.com/questions/40351479/php-salt-option-to-password-hash-is-deprecated
so_39260573
How to get count of distinct XML nodes?
I'm having trouble using references in recursive calls. What I am trying to accomplish is to describe an XML document in terms of the max count of distinct nodes within a respective element - without knowing any of the node element names in advance. Consider this document: You can see that a has either 1 or 2 nodes and...
While your solution works, and pretty efficiently given that it operates in time ( where is the number of nodes in the tree and is the number of vertices ), I figured I'd propose an alternative solution that doesn't rely on arrays or references and is more generalized to work, not just for XML, but for any DOM tree. Th...
[ "$result = [ \"Data\" =&gt; [ \"max_count\" =&gt; 1, \"elements\" =&gt; [ \"Record\" =&gt; [ \"max_count\" =&gt; 2, \"elements\" =&gt; [ \"SAMPLE\" =&gt; [ \"max_count\" =&gt; 2, \"elements\" =&gt; [ \"TITLE\" =&gt; [ \"max_count\" =&gt; 1 ], \"SUBTITLE\" =&gt; [ \"max_count\" =&gt; 1 ], \"AUTH\" =&gt; [ \"max_coun...
php
9.5
stackoverflow
[ "php", "xml" ]
8
https://stackoverflow.com/questions/39260573/how-to-get-count-of-distinct-xml-nodes
so_39260300
Preventing JSON domain spoofing
Here's the scenario. A customer already has an eCommerce site where they are collecting shipping address info and credit card data. However, they sign up with a SaaS service that allows them to easily change their credit card form to also collect fullnames and emails (not credit card info) into a marketing system for o...
TL;DR: If you're using a purely client-side integration (just javascript), there's no way to completely secure the request. Accidentally/intentionally sending data to the wrong client You can mitigate this by using non-sequential, random UUIDs as account IDs. For example, if an account ID looks like 100001, then someon...
[]
php
7
stackoverflow
[ "php", "jquery", "security", "hash", "public-key" ]
4
https://stackoverflow.com/questions/39260300/preventing-json-domain-spoofing
so_39260080
Escaping a string with quotes in Laravel
I would like to insert the content of an excel file into my database. I simply use a raw query to achieve this. The controller function My Problem: There are names in the excel file like Mc'Neal, so I get an error message. How can I escape the apostrophe in laravel?? I am really new to laravel and would be happy for an...
have you tried ? http://php.net/manual/en/function.addslashes.php
[ "public function uploadExcel() { $filename = Input::file('import_file')-&gt;getRealPath(); $file = fopen($filename, \"r\"); $count = 0; while (($emapData = fgetcsv($file, 10000, \"\\t\")) !== FALSE) { $count++; if($count&gt;1) { DB::statement(\"INSERT INTO `members` ( member_title, member_first_name, member_name_af...
php
8.5
stackoverflow
[ "php", "laravel", "escaping", "mysql-real-escape-string" ]
21
https://stackoverflow.com/questions/39260080/escaping-a-string-with-quotes-in-laravel
so_77704354
transform a &quot;curl&quot; query into &quot;axios&quot;
I'm trying to call the Spotify API, and it works well with curl, but when I try to do it with axios in my NestJS app, I got an error. Here is the &quot;curl&quot; command that works and returns my access token : And I've tried to transform it into an axios request like this : So my code is correctly displayed in my con...
Looking your curl it think you can do like this.
[ "curl -X &quot;POST&quot; &quot;https://accounts.spotify.com/api/token&quot; \\ -d &quot;grant_type=authorization_code&quot; \\ -d &quot;code={MY_AUTHORIZATION_CODE}&quot; \\ -d &quot;redirect_uri={MY_REDIRECT_URI}&quot; \\ -d &quot;client_id={MY_CLIENT_ID}&quot; \\ -d &quot;client_secret={MY_CLIENT_SECRET}&quot; \...
typescript
7.38
stackoverflow
[ "curl", "axios", "nestjs", "spotify" ]
3
https://stackoverflow.com/questions/77704354/transform-a-curl-query-into-axios
so_73913180
How can I use single transaction with multiple query in repository mode in nestjs-typeorm
I have a setup for my NestJS application in which I am using typeorm with a PostgreSQL database. In the setup, I am using repository mode to query the database. Now I want to use database transactions with my queries, but I am not able to use transactions because I am using one transaction with multiple queries from di...
I have found a solution, where I can use the repository and transaction just like sequelize, it is using the manager provided when we start a transaction, there is a method inside the manager object, it can be used to do query using a specific repository. So what I have done is created a BaseService and everytime I hav...
[ "@Injectable() export class EntityOneService extends BaseService&lt;EntityOne&gt; { repository: Repository&lt;EntityOne&gt;; constructor(private connection: Connection) { super(); this.repository = this.connection.getRepository(EntityOne); } }", "import { Injectable } from '@nestjs/common'; import { Connection, R...
sql
8.75
stackoverflow
[ "javascript", "typescript", "postgresql", "nestjs", "typeorm" ]
2
https://stackoverflow.com/questions/73913180/how-can-i-use-single-transaction-with-multiple-query-in-repository-mode-in-nestj
so_73907223
how to return buffer to a streamablefile in nestjs !? the error occured is Argument of type &#39;string&#39; is not assignable to parameter of type &#39;Buffer&#39;
The description: I can't return a StreamableFile from buffer , i've tried but doesn't work which shows the error below French version of issue: Aucune surcharge ne correspond à cet appel. La surcharge 1 sur 2, '(buffer: Buffer): StreamableFile', a généré l'erreur suivante. L'argument de type 'string' n'est pas attribua...
The error is explicitly clear: you can't pass a to , you have to pass either a or a . To create a buffer from a string, you can use
[ "async FindCommands(@Res({ passthrough: true }) response, @Query() query: DateRangQueryVm): Promise&lt;StreamableFile&gt; { const filesToPdf= await this.commandsService.getCommands(query.startDate, query.endDate); const nommation= `commands.pdf`; response.setHeader('Content-Type', `application/pdf`); response.setHe...
typescript
8.38
stackoverflow
[ "node.js", "typescript", "nestjs" ]
3
https://stackoverflow.com/questions/73907223/how-to-return-buffer-to-a-streamablefile-in-nestjs-the-error-occured-is-argum
so_73906073
Nestjs custom validation pipe Undefined
I got a problem in my custom validation pipe I'm trying to verify if the id passed exist in an other table. it telling me that it can not read property of undefined but I console log the id and you can see that its correcly console above the error message. I've also check if my findOne works in a route and its doing fi...
I have found the solution I had to put UseContainer in the main.ts. It will allow class-validator to use NESTJS dependency injection container. However i don't know if it's the best way to do it
[ "import { Injectable } from '@nestjs/common'; import { ValidatorConstraint, ValidatorConstraintInterface, } from 'class-validator'; import { ExerciceRepository } from 'src/Infrastructure/repository/exercice.repository'; @ValidatorConstraint({ name: 'ExerciceExists', async: true }) @Injectable() export class Exercic...
typescript
9
stackoverflow
[ "javascript", "pipe", "nestjs" ]
4
https://stackoverflow.com/questions/73906073/nestjs-custom-validation-pipe-undefined
so_73905987
TypeORM No metadata for \&quot;MyEntity\&quot; was found
I 1. have the following datasource on &quot;app-data-source.ts&quot; Which uses the entity App on &quot;entities/app.ts&quot; And the following module that queries the Entity App (Shown above on number 2). However I get the following Error.
Apparently I was not initializing the connection by calling function before performing the query.🤦‍♂️ Like so.
[ "import { DataSource } from &quot;typeorm&quot;; import { App } from &quot;./entities/app&quot;; export const appDataSource = new DataSource({ type: 'postgres', host: process.env.CONFIG_DB_HOST, port: 5432, username: process.env.CONFIG_DB_USER, password: process.env.CONFIG_DB_PASSWORD, database: process.env.CONFIG_...
sql
8.12
stackoverflow
[ "postgresql", "nestjs", "datasource", "typeorm" ]
9
https://stackoverflow.com/questions/73905987/typeorm-no-metadata-for-myentity-was-found
so_73898438
Does the Nestjs controller method have to be async if it returns a promise?
Very simple general question: So in such a case, do I have to make the controller method async? My understanding is that this is not necessary. NestJS will resolve the returned promise automatically. Making the method async is only needed if I wanna inside. Is this correct?
Technically, it's not necessary, Nest will view the promise as is and resolve it before sending the response, but it's generally a good practice to mark your promise returning methods as , just to stay in the habit and be clear about what it is returning
[ "@Controller('something') class SomeController { @Get() foobar() { return foo() // this returns a promise } }" ]
typescript
9.75
stackoverflow
[ "asynchronous", "controller", "nestjs" ]
14
https://stackoverflow.com/questions/73898438/does-the-nestjs-controller-method-have-to-be-async-if-it-returns-a-promise
so_73897919
Select by category and count by status mongodb
I have a list of records and want to group by categories and after this count buy isArchived status. I'm just starting to learn MongoDB and I can't do the query described below, I would appreciate your tips. This is peace of data. This is request Now I receive like this But I want to receive it like this What should be...
Group by only and calculate the and counts by checking the condition, archived condition is if is true then return 1 otherwise 0 unArchived condition is if is true then return 0 otherwise 1 Playground
[ "[ { &quot;_id&quot;: &quot;63356af2d77a56d764f362e4&quot;, &quot;noteName&quot;: &quot;string&quot;, &quot;category&quot;: &quot;IDEA&quot;, &quot;content&quot;: &quot;string&quot;, &quot;isArchived&quot;: true, &quot;createdAt&quot;: &quot;2022-09-29T09:52:50.477Z&quot;, &quot;updatedAt&quot;: &quot;2022-09-29T09...
typescript
8.75
stackoverflow
[ "node.js", "mongodb", "nestjs" ]
2
https://stackoverflow.com/questions/73897919/select-by-category-and-count-by-status-mongodb
so_63675108
How to make a dynamic roles guard, to work in both controllers and handlers
I'm defining a roles guard like this: in this roles example it works only in a controller level like this: But i want it to work dynamically with both, at controller level, and handler level. so i can appy a for every route in the controller, and for some routes in that controller. So to do this i need to change the re...
Nest's has a built-in method to merge the metadata set on controllers and route handlers with which will merge the metadata from the class and the method. To use it you would do something like If you wanted to get just one set of metadata and have a fallback (say if you want only the handler metadata if it exists and i...
[ "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { Observable } from 'rxjs'; import { User } from './user.entity'; @Injectable() export class RolesGuard implements CanActivate { constructor( private reflector: Reflector, ) { } async matchR...
typescript
10.25
stackoverflow
[ "nestjs", "nestjs-passport" ]
14
https://stackoverflow.com/questions/63675108/how-to-make-a-dynamic-roles-guard-to-work-in-both-controllers-and-handlers
so_63664322
How to use jest.spyOn with NestJS Transaction code on Unit Test
NestJS provides a sample Transaction code on ( https://docs.nestjs.com/techniques/database#transactions ), and I now would like to create Unit test script against the code. Here are the some dependent files: Here is the unit test script. I am close to accomplish but still I am getting from with the setup below:
will return difference instance of . This mean of will not reference to in of function. Then your mock does not make sense. Keep it simple, make as a &quot;global&quot; variable, then binding it to , this mean we will have the same &quot;variable&quot; when we call . Updated content, class.
[ "@Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column({type: 'text', name: 'first_name'}) firstName: string; @Column({type: 'text', name: 'last_name'}) lastName: string; @Column({name: 'is_active', default: true}) isActive: boolean; }", "@Injectable() export class UsersService { constructor...
typescript
8.88
stackoverflow
[ "node.js", "jestjs", "nestjs" ]
3
https://stackoverflow.com/questions/63664322/how-to-use-jest-spyon-with-nestjs-transaction-code-on-unit-test
so_63639171
How to mock nestjs-redis with jest
I am trying to mock and spy on the redis set method in my nestjs setup, but I don't think that it is working as it should. I suspect that it is not possible to use spyOn with a nested method as in this context? How should I mock redis to be able to use spyOn on ? The library used for redis in this case is .
You don't have to use to check the arguements that have been passed to the function. You can simply create a : Creating a mock is much simpler this way as you only have to create the mocked objects and test the functions the use. Here your spy is and I reorganized your testing file so the spy function has a default val...
[ "const mockRedis = { set: jest.fn().mockResolvedValue(undefined), }; const mockRedisService = { getClient: jest.fn(() =&gt; mockRedis), }; beforeEach(async () =&gt; { const moduleRef = await Test.createTestingModule({ providers: [ { provide: RedisService, useValue: mockRedisService }, ], }).compile(); }); it('...',...
typescript
9
stackoverflow
[ "redis", "jestjs", "nestjs" ]
4
https://stackoverflow.com/questions/63639171/how-to-mock-nestjs-redis-with-jest
so_63630805
How to set default time zone in Nestjs?
I tried below script but it didn't work. [System Information] OS Version : Linux 5.4 NodeJS Version : v12.18.3 NPM Version : 6.14.6 [Nest CLI] Nest CLI Version : 7.4.1 [Nest Platform Information] platform-express version : 7.0.0 passport version : 7.0.0 typeorm version : 7.1.0 common version : 7.0.0 config version : 0....
In a REPL, this is working as expected. I would assume you need to set your start command as
[ "{ &quot;scripts&quot;: { &quot;start&quot;: &quot;TZ='UTC' nest start&quot; } }" ]
typescript
8.5
stackoverflow
[ "nestjs", "nestjs-config" ]
23
https://stackoverflow.com/questions/63630805/how-to-set-default-time-zone-in-nestjs
so_63618612
NestJS - Use service inside Interceptor (not global interceptor)
I have a controller that uses custom interceptor: Controller: I have also I SignService, which is wrapper around NestJwt: SignService module: And Finally SignInterceptor: SignService works properly and I use it. I would like to use this as an interceptor How can I inject SignService in to SignInterceptor, so I can use ...
I assume that is part of the : Then inject the into the : Because you use to use the interceptor in your controller Nestjs will instantiate the for you and handle the injection of dependencies.
[ "@UseInterceptors(SignInterceptor) @Get('users') async findOne(@Query() getUserDto: GetUser) { return await this.userService.findByUsername(getUserDto.username) }", "@Module({ imports: [ JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) =&gt; ({ privateKey: config...
typescript
10.5
stackoverflow
[ "nestjs", "nestjs-jwt" ]
18
https://stackoverflow.com/questions/63618612/nestjs-use-service-inside-interceptor-not-global-interceptor
so_63615262
Sentry not getting TypeScript source maps when integrated with NestJS
I've created a small NestJS project recently which I attempting to integrate Sentry into. I have followed the instructions on the Nest-Raven package readme, along with the instructions provided by Sentry for TypeScript integration . Unfortunately I cannot seem to get Sentry to display the TypeScript sourcemaps, only th...
So it turns out the issue was the directory I was providing to the constructor. I had initially copied the implementation from the Sentry Typescript documentation , but during debugging I found that and were returning different paths. Since was returning a truthy value, the path being given to Sentry was the one that i...
[ "import { NestFactory } from '@nestjs/core'; import { RewriteFrames } from '@sentry/integrations'; import * as Sentry from '@sentry/node'; import { AppModule } from './app.module'; // This allows TypeScript to detect our global value declare global { // eslint-disable-next-line @typescript-eslint/no-namespace names...
typescript
10
stackoverflow
[ "typescript", "nestjs", "source-maps", "sentry" ]
12
https://stackoverflow.com/questions/63615262/sentry-not-getting-typescript-source-maps-when-integrated-with-nestjs
so_63608615
Nest js upload is not saving file
I'm following the documentation for File upload , my endpoint is getting the file, but the file is not stored. I'm using the same configuration than NesJS My file, I added the import for: But the file is not stored in the directory . The complete log is: (Yes, including the ) What am I doing wrong?
you should specify the destination. multer options or you can use createWriteStream in module to save file by yourself.
[ "@Post('upload') @UseInterceptors(FileInterceptor('file')) uploadFile(@UploadedFile() file) { console.log(file); }", "MulterModule.register({ dest: './uploads' })", "undefined { fieldname: 'file', originalname: 'nopornimage.png', encoding: '7bit', mimetype: 'image/png', buffer: &lt;Buffer 89 50 4e 47 0d 0a 1a 0...
typescript
9
stackoverflow
[ "nestjs", "multer" ]
18
https://stackoverflow.com/questions/63608615/nest-js-upload-is-not-saving-file
so_63585893
GraphQL + NestJS - how can I access @Args in a guard?
I need the to somehow access the from inside the guard so as to check if the sender has the assigned to his account. Any idea how I could implement it? Is it possible to access the passed argument from the context?
You can use GqlExecutionContext for it, like: @nestjs/graphql version: ^7.6.0
[ "@Query(() =&gt; [Person]) @UseGuards(ObjectMatch) async pplWithObject(@Args('objectId') id: string): Promise&lt;Person[]&gt; { return await this.objService.getPeopleWithObject(id); }" ]
typescript
8.5
stackoverflow
[ "graphql", "nestjs", "guard", "args" ]
16
https://stackoverflow.com/questions/63585893/graphql-nestjs-how-can-i-access-args-in-a-guard
so_63584034
NestJS, PortsgreSQL and TypeORM - Migrations not running properly
When trying to run the TypeORM Migrations, either automatically in the application startup or manually via the TypeORM CLI, only the migrations table gets created (and it stays empty). The migration files themselves are not being executed. Here is my tsconfig.json Here is my package.json Here is my ormconfig.json The m...
That was a silly one! I guess some times the simplest problems are the hardest to spot. The problem was in the file. I removed this empty space ( ) and everything worked just fine.
[ "{ &quot;compilerOptions&quot;: { &quot;module&quot;: &quot;commonjs&quot;, &quot;declaration&quot;: true, &quot;removeComments&quot;: true, &quot;emitDecoratorMetadata&quot;: true, &quot;experimentalDecorators&quot;: true, &quot;allowSyntheticDefaultImports&quot;: true, &quot;target&quot;: &quot;es2017&quot;, &quo...
typescript
9.25
stackoverflow
[ "postgresql", "nestjs", "typeorm" ]
6
https://stackoverflow.com/questions/63584034/nestjs-portsgresql-and-typeorm-migrations-not-running-properly
so_63579162
How to reuse Redis connection inside Typeorm cache config in NestJs
I am using Redis to cache queries inside TypeOrm. but the problem is, TypeOrm and Redis package is opening the separate connection, i just want to reuse the same connection for both. this is typeorm config: i am using @svtslv/nestjs-ioredis package for redis: and using this package, i am able to access redis inside my ...
After some digging in the TypeORM code base I came across two solutions (wiil one the other is a bit hacky and my case issues) ORM CustomQueryResultCache According to the doc, you can implement your own cache handler see: https://github.com/typeorm/typeorm/blob/master/docs/caching.md . This is the better but harder sol...
[ "import { TypeOrmModuleOptions } from '@nestjs/typeorm'; import { Constants } from '../utils/Constants'; export const typeOrmConfig: TypeOrmModuleOptions = { type: Constants.DB_TYPE, host: Constants.DB_HOST, port: Constants.DB_PORT, username: Constants.DB_USER_NAME, <REDACTED_SECRET>.DB_PASSWORD, database: Constant...
typescript
9.38
stackoverflow
[ "node.js", "typescript", "nestjs", "typeorm", "node-redis" ]
7
https://stackoverflow.com/questions/63579162/how-to-reuse-redis-connection-inside-typeorm-cache-config-in-nestjs
so_79903218
How to serialize Date in response without breaking Swagger / OpenAPI?
I'm building a NestJS API using the package for request/response validation and Swagger generation. I have a domain entity like this: My Zod response schema: Controller: My entity returns a Date value: If I define the response schema as: Swagger works correctly, but the runtime validation fails because the returned val...
Use z.coerce.date() with a custom transformer, or use z.string().datetime() with serialization The cleanest approach is to transform the Date to a string at the schema level, which satisfies both runtime validation and Swagger generation.
[ "export class UserEntity { constructor( public readonly id: string, public readonly username: string, public readonly hashPassword: string, public readonly is_active: boolean, public readonly created_at: Date, public readonly updated_at: Date | null, ) {} }", "import { z } from &quot;zod&quot; import { createZodD...
typescript
9
stackoverflow
[ "nestjs", "swagger", "openapi", "zod" ]
4
https://stackoverflow.com/questions/79903218/how-to-serialize-date-in-response-without-breaking-swagger-openapi
so_79861105
How to get a build completion message for nest js?
I run command I want to receive a message when the build is complete. I use --builder tsc
If this is for a script, you can check the exit code of the previous command and if it equals then it was a success. Or you could chain it with a to move on if/when it succeeds. The command doesn't output a message on success, the terminal is just set to a state ready to accept another command as the command is finishe...
[]
typescript
5.75
stackoverflow
[ "javascript", "typescript", "nestjs", "tsc", "nestjs-config" ]
2
https://stackoverflow.com/questions/79861105/how-to-get-a-build-completion-message-for-nest-js
End of preview. Expand in Data Studio

Tech QA — Stack Overflow & GitHub Debug Dataset

A curated, quality-filtered technical question-answering dataset collected from Stack Overflow and GitHub Issues, covering 9 software engineering domains. Designed for instruction fine-tuning of code-capable language models.


📋 Dataset Summary

Property Value
Total examples ~20,000
Languages English
Format JSONL
Sources Stack Overflow, GitHub Issues
Domains 9 (see below)
Quality filter score ≥ 5.0
License CC BY-SA 4.0

🗂️ Domain Distribution

Domain Description
python Python, Django, Flask, FastAPI, NumPy, Pandas
javascript Node.js, React, Vue.js, Express
typescript TypeScript, Angular, NestJS
php PHP, Laravel, Symfony
wordpress WordPress, WooCommerce, Gutenberg
sql MySQL, PostgreSQL, SQLite, query optimization
devops Docker, Kubernetes, GitHub Actions, Terraform
shell_scripting Bash, Linux, shell tools
system_design Architecture, design patterns, scalability

📁 Data Fields

{
  "id": "so_12345678",
  "title": "How to filter a list in Python using conditions?",
  "question": "I have a list of integers and want to keep only even numbers...",
  "answer": "You can use list comprehension or the filter() function...",
  "codes": ["filtered = [x for x in nums if x % 2 == 0]"],
  "technology": "python",
  "quality_score": 8.5,
  "source": "stackoverflow",
  "tags": ["python", "list", "filter"],
  "score": 42,
  "url": "https://stackoverflow.com/questions/12345678"
}
Field Type Description
id string Unique identifier (so_ or gh_ prefix)
title string Question title
question string Full question body (HTML stripped)
answer string Best/accepted answer (HTML stripped)
codes list[string] Extracted code blocks from question + answer
technology string Detected domain (one of 9 above)
quality_score float Composite quality score (0–10+)
source string "stackoverflow" or "github"
tags list[string] Original tags from source
score int Combined vote score
url string Source URL

⚙️ Quality Scoring

Each example is scored automatically using a heuristic function:

Signal Weight
Question length ≥ 40 chars +1.0
Question length ≥ 120 chars +1.0
Answer length ≥ 40 chars +1.5
Answer length ≥ 120 chars +1.5
Has code block +1.5
Has ≥ 2 code blocks +0.5
Vote score (capped at 16) +up to 2.0
Accepted answer +1.0
Known domain +0.5

Only items with quality_score ≥ 5.0 are included.


🔍 Collection Pipeline

  • Stack Overflow: Fetched via the Stack Exchange API v2.3. Only questions with an accepted answer and a minimum vote score are included. Covers monthly time windows from 2015 to present.
  • GitHub Issues: Fetched via the GitHub REST API. Only issues with permissive licenses (MIT, Apache-2.0, BSD, ISC, MPL-2.0) are included.
  • Deduplication: Exact hash deduplication + SimHash near-duplicate detection (Hamming distance ≤ 6).
  • PII Redaction: Emails, IPs, AWS keys, GitHub tokens, and generic secrets are redacted.

⚠️ Known Limitations

  • Language: Content is primarily in English. Turkish language coverage is minimal.
  • Task type: Dataset is focused on debug / problem-solving QA. Conceptual / explanatory content (e.g. "What is GET vs POST?") is underrepresented.
  • Code bias: Quality scoring favors code-heavy answers. Pure explanation items may be filtered out.
  • No instruction format: Items are raw Q&A pairs, not formatted as system/user/assistant turns. Instruction formatting is required before use in chat-style fine-tuning.

💡 Recommended Usage

This dataset works best for:

  • LoRA / QLoRA fine-tuning of code-capable base models
  • Continued pre-training on technical content
  • Retrieval-augmented generation (RAG) knowledge base

For instruction fine-tuning, convert to chat format first:

def to_chat_format(example):
    return {
        "messages": [
            {"role": "user", "content": example["question"]},
            {"role": "assistant", "content": example["answer"]}
        ]
    }

📜 License

Stack Overflow content: Licensed under CC BY-SA 4.0.
GitHub content: Sourced only from repositories with permissive OSI-approved licenses.

Attribution required for Stack Overflow content per CC BY-SA 4.0 terms.



🇹🇷 Türkçe Açıklama

Veri Seti Özeti

Stack Overflow ve GitHub Issues'dan toplanan, kalite filtreli teknik soru-cevap veri setidir. 9 farklı yazılım mühendisliği alanını kapsayan bu veri seti, kod üretebilen dil modellerinin instruction fine-tuning süreçleri için tasarlanmıştır.


📋 Temel Bilgiler

Özellik Değer
Toplam örnek ~20.000
Dil İngilizce
Format JSONL
Kaynaklar Stack Overflow, GitHub Issues
Alan sayısı 9 (aşağıda)
Kalite filtresi skor ≥ 5.0
Lisans CC BY-SA 4.0

🗂️ Alan Dağılımı

Alan Açıklama
python Python, Django, Flask, FastAPI, NumPy, Pandas
javascript Node.js, React, Vue.js, Express
typescript TypeScript, Angular, NestJS
php PHP, Laravel, Symfony
wordpress WordPress, WooCommerce, Gutenberg
sql MySQL, PostgreSQL, SQLite, sorgu optimizasyonu
devops Docker, Kubernetes, GitHub Actions, Terraform
shell_scripting Bash, Linux, kabuk araçları
system_design Mimari, tasarım desenleri, ölçeklenebilirlik

⚠️ Bilinen Kısıtlamalar

  • Dil: İçerik büyük ölçüde İngilizce'dir. Türkçe kapsam minimumdur.
  • Görev tipi: Veri seti hata ayıklama / problem çözme odaklıdır. Kavramsal açıklamalar (ör. "GET ve POST arasındaki fark nedir?") yeterince temsil edilmemektedir.
  • Kod ağırlığı: Kalite puanlaması kod içeren cevapları tercih eder. Saf açıklama içerikli örnekler filtrelenmiş olabilir.
  • Instruction formatı yok: Örnekler ham S/C çiftleridir; chat tabanlı fine-tuning için system/user/assistant formatına dönüştürülmesi gerekir.

🔧 Toplama Altyapısı

  • Stack Exchange API v2.3 üzerinden aylık zaman pencereli tarama (2015'ten günümüze)
  • GitHub REST API üzerinden yalnızca izin verici lisanslı depolardan (MIT, Apache-2.0, BSD, ISC, MPL-2.0)
  • Tam hash + SimHash yakın-kopya tespiti ile tekilleştirme
  • Otomatik PII temizliği (e-posta, IP, token, şifre)

📜 Lisans

Stack Overflow içeriği: CC BY-SA 4.0 ile lisanslanmıştır.
GitHub içeriği: Yalnızca OSI onaylı izin verici lisanslara sahip depolardan alınmıştır.

Stack Overflow içeriği için CC BY-SA 4.0 koşulları gereği atıf zorunludur.

Downloads last month
-