satoshi-2000/llms-suitable huggingface dataset:
Question: Get product version from a custom action

I have a Wix installer.
In the Product.wxs file, I have the below piece of code:
<Product Id="*"
    Name="$(var.PRODUCT_NAME)"
    Language="1033"
    Version="!(bind.FileVersion.myDLLfile)"
    Manufacturer="$(var.CompanyName)"
    UpgradeCode="{D00BA432-7798-588A-34DF-34A65378FD45}">

In the Features.wxs, I have the myDLLfile defined as component:
<Component Id="myDLLfile"
    Guid="{30550881-053F-768D-88B7-BB9853B23C51}">
    <File Id="myDLLfile"
        Source="$(var.dllDir)\myDLLfile.dll"
        KeyPath="yes"
        Checksum="yes"/>
</Component>

Now, I would like to know if from a custom action in C# I can get that same Product Version (which corresponds to the version of the myDllfile.dll). Is it possible? If so, how?


Answer:
The easiest way is probably to store the value in a Property and read that property in the custom action. The bind variable syntax would make setting the property easy.
   <Property Id="ThisIsASillyThingToNeedToDo" Value="!(bind.FileVersion.myDLLfile)" />
Question: Why does Mysql change query execution plan based on query parameters?

I have the following query.
SELECT *
FROM user u
LEFT JOIN operator o ON o.id = u.id
WHERE u.user_type_id IN (2,4) AND u.is_enabled = 1 AND u.office_id = 225

If I run explain on the query above, it shows that it uses the index IX_user_type for the table user.
If I just change the office_id comparison value like the following, the execution plan changes.
SELECT *
FROM user u
LEFT JOIN operator o ON o.id = u.id
WHERE u.user_type_id IN (2,4) AND u.is_enabled = 1 AND u.office_id = 32365487

In this case, the explain shows that the indexes used for the table user are fk_user_office,IX_user_is_enabled.
I made some tests and would say, performance wise, the first execution plan is much better than the second one. Now, I know I can force Mysql to use the index I want but, I would like to understand why this happens. Why would Mysql pick an index instead of another based on a query parameter?


Answer:
MySQL may decide not to use the index on office_id if the value you are searching for is too common.
By analogy, why doesn't a book include common words like "the" in the index at the back of the book? Because such common words occur on a majority of pages in the book. It's unnecessary to keep a list of those pages under the respective word in the index, because it's easier to tell the reader to read all the pages in the book, without the index lookup.
Similarly, if MySQL estimates that a given value you are searching for occurs on a high enough portion of the pages, it looks for another index if you have other conditions, and if none are found, then it resorts to a table-scan.
In this case, I'd ask if you can confirm that office_id 225 is very common in this table.

One more thought: The best index of all for the query you show would be a compound index on (office_id, is_enabled, user_type). Then it would be able to use that index to narrow down the search by all three columns at once.
You might like my presentation How to Design Indexes, Really or the video. I also have a chapter on index design in my book SQL Antipatterns, Volume 1:
Avoiding the Pitfalls of Database Programming.
Question: Save the output of bigquery in JSON from python

How can I modify this script to be able to see/print some of the results and write the output in JSON :
from google.cloud import bigquery


def query_stackoverflow(project_id="gwas-386212"):
    client = bigquery.Client()
query_job = client.query(
        """
        WITH
  SNP_info AS (
  SELECT
    CONCAT(CAST(rs_id AS string)) AS identifier
  FROM
  `gwas-386212.gwas_dataset_1.SNPs_intergenic_vep_pha005199`)
SELECT
  *
FROM
  SNP_info
JOIN (
  SELECT
    CONCAT(CAST(rs_id AS string)) AS identifier,
chr_id AS chr_id,
position AS position, 
ref_allele AS ref,
alt_allele AS alt,
most_severe_consequence AS most_severe_consequence, 
gene_id_any_distance AS gene_id_any_distance,
gene_id_any AS gene_id_any,
gene_id_prot_coding_distance AS gene_id_prot_coding_distance, 
gene_id_prot_coding AS gene_id_prot_coding
 FROM
    `bigquery-public-data.open_targets_genetics.variants`) variants
ON
  SNP_info.identifier = variants.identifier""" 
  )
results = client.query(query)

for row in results:
    title = row['identifier']
    identifier = row['identifier']
    #print(f'{identifier}')

This is just printing a column the intentifier. i want to save the resulted table in JSON format. The JSOn from the google cloud platform should look something like this:
[{
  "identifier": "rs62063022",
  "identifier_1": "rs62063022",
  "chr_id": "17",
  "position": "51134537",
  "ref": "T",
  "alt": "G",
  "most_severe_consequence": "intergenic_variant",
  "gene_id_any_distance": "13669",
  "gene_id_any": "ENSG00000008294",
  "gene_id_prot_coding_distance": "13669",
  "gene_id_prot_coding": "ENSG00000008294"
}, {
  "identifier": "rs12944420",
  "identifier_1": "rs12944420",
  "chr_id": "17",
  "position": "42640692",
  "ref": "T",
  "alt": "C",
  "most_severe_consequence": "intergenic_variant",
  "gene_id_any_distance": "18592",
  "gene_id_any": "ENSG00000037042",
  "gene_id_prot_coding_distance": "18592",
  "gene_id_prot_coding": "ENSG00000037042"
},



Answer:
Check out json documentation for further information.
records = [dict(row) for row in results]
out_file = open("bigquery_response.json", "w")
json.dump(records , out_file, indent = 6)
out_file.close()
Question: How to rewrite sync method using SwiftUI?

Now I'm using UIImage sync extension.
struct PostView: View {
    let url: String
    
    var body: some View {        
        PrivateImageView(image: UIImage(url:url))
     }
}

extension UIImage {
    public convenience init(url: String) {
        let url = URL(string: url)
        do {
            let data = try Data(contentsOf: url!)
            self.init(data: data)!
            return
        } catch let err {
            print("Error : \(err.localizedDescription)")
        }
        self.init()
    }
}

When I post a image, I got the error Synchronous URL loading of http://local.host/images/123.jpeg should not occur on this application's main thread as it may lead to UI unresponsiveness. Please switch to an asynchronous networking API such as URLSession. at try Data(contentsOf: url!).
In PostView I use PrivateImageView.
To use the view I have to designate the argument like this PrivateImageView(image: UIImage(xxxxxxxxx)).
I mean I have to use UIImage() not AsyncImage.
I don't know how to change convenience init to adjust to PrivateImageView.
Please tell me how to use an async function in this context.


Answer:
There is no way to get a data from the inter/intranet synchronously you have to use an async method and account for the time it takes to download.
extension String {
    public func getUIImage() async throws -> UIImage {
        guard let url = URL(string: self) else {
            throw URLError(.badURL)
        }
        
        let (data, response) = try await URLSession.shared.data(from: url)
        
        guard let httpResponse = response as? HTTPURLResponse else {
            throw URLError(.badServerResponse)
        }
        
        guard httpResponse.statusCode == 200 else {
            throw URLError(URLError.Code(rawValue: httpResponse.statusCode))
        }
        
        guard let image = UIImage(data: data) else {
            throw URLError(.fileDoesNotExist)
        }
        return image
    }
}

extension UIImage {
    static public func fromURL(url: String) async throws -> UIImage {
        let image = try await url.getUIImage()
        return image
    }
}

You can rewrite PostView to something like.
struct PostView: View {
    let url: String
    @State private var uiImage: UIImage?
    var body: some View {
        Group{
            if let uiImage {
                PrivateImageView(image: uiImage)
            } else {
                ProgressView() //Show this while downloading
                    .task {
                        do {
                            self.uiImage = try await url.getUIImage()
                            // or
                            // self.uiImage = try await UIImage.fromURL(url: url)
                        } catch {
                            print(error)
                        }
                    }
            }
        }
    }
}
Question: Self signed certificate not working on localhost IIS

I have am setting up a very simple test site on my localhost under IIS which needs to be accessible locally from https.  IU have followed the steps below:

In IIS for my local server, I have created a self signed certificate and stored in the "Personal" store
I have added a https binding for my test site to this new certificate, the hostname is testite and the port 7001
Added the entry '127.0.0.1   testsite' to hosts file.

When I try to access https://testsite/index.html through the browser, the browser returns the following error:
NET::ERR_CERT_COMMON_NAME_INVALID
Same problem soccurs if I add the port number to the url, i.e: https://testsite:7001/index.html
More informatiom on the error shows the following:
This server could not prove that it is testsite; its security certificate is from Muzz2. This may be caused by a misconfiguration or an attacker intercepting your connection.



Answer:
The solution involved using Powershell rather than IIS manager to generate the self signed certificate.  ISS always used the machine name rather than the sitename as the common name.
The powershell command I used was as follows:
New-SelfSignedCertificate -DnsName testsite -CertStoreLocation cert:\LocalMachine\My
After which mmc was used to place the certificate in the Trusted Root Certification Authorities, and the certificated bindings updated in IIS as you you usually would.
Question: How to do conditional compilation with Zig?

For example, I can add definitions for C/C++ preprocessor with CMake
add_definitions(-DFOO -DBAR ...)

and then I can use them for conditional compilation
#ifdef FOO
   code ...
#endif

#ifdef BAR
   code ...
#endif


Is there a way to do the same thing with Zig and its build system using compilation arguments or something like that?


Answer:
You can do something similar using the build system. This requires some boilerplate code to do the option handling. Following the tutorial on https://zig.news/xq/zig-build-explained-part-1-59lf for the build system and https://ziggit.dev/t/custom-build-options/138/8 for the option handling:

Create a separate file called build.zig that contains a function build():

const std = @import("std");

pub fn build(b: *std.build.Builder) !void {
    const build_options = b.addOptions();
    // add command line flag
    // and set default value
    build_options.addOption(bool, "sideways", b.option(bool, "sideways", "print sideways") orelse false);

    // set executable name and source code
    const exe = b.addExecutable("hello", "hello.zig");
    exe.addOptions("build_options", build_options);
    // compile and copy to zig-out/bin
    exe.install();
}


Use the option for conditional compilation in a separate file hello.zig using @import("build_options"):

const std = @import("std");

pub fn main() !void {
    const print_sideways = @import("build_options").sideways;
    const stdout = std.io.getStdOut().writer();
    if (print_sideways) {
       try stdout.print("Sideways Hello, {s}!\n", .{"world"});
    } else {
       try stdout.print("Regular Hello, {s}!\n", .{"world"});
    }
}


Compile with:

zig build -Dsideways=true


Executing zig-out/bin/hello gives the following output:

Sideways Hello, world!
Question: Cognito JWT Authorize in ASP.NET Core 6 Web API

How can I configure my ASP.NET Core 6 Web API controllers to use AWS Cognito authorization?
This is the code I wrote in my program.cs file:
var AWSconfiguration = builder.Configuration.GetSection("AWS:Cognito");
var userPoolId = AWSconfiguration["UserPoolId"];
var clientId = AWSconfiguration["ClientId"];
var region = AWSconfiguration["Region"];

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = $"https://cognito-idp.{region}.amazonaws.com/{userPoolId}";
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidIssuer = $"https://cognito-idp.{region}.amazonaws.com/{userPoolId}",
        ValidAudience = clientId,
        
    };
});

I'm getting this error:

www-authenticate: Bearer error="invalid_token",
error_description="The audience 'empty' is invalid"

I validated my clientID in the AWS console.
Thanks for the help


Answer:
Cognito access tokens don't have an audience claim - though ideally they should. In other authorization servers, APIs check the received access token has the expected logical name, such as api.mycompany.com.
For Cognito you will need to configure .NET to not validate the audience, similar to this. Other token validation parameters are derived from the metadata endpoint derived from the issuer base URL:
private void ConfigureOAuth(IServiceCollection services)
{
    services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = this.configuration.IssuerBaseUrl;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
            };
        });

    services.AddAuthorization(options => 
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    });
}


The FallbackPolicy then ensures that authentication is applied globally, except for endpoints annotated with [AllowAnonymous].
Question: How to pass arguments in cron job function

Im totaly new in wordpress php and cron. So, I have a task. I need to take data from a form and put it into a cron function.
This is me code. I created custom plugin page in wordpress admin panel and try to run this code.
actually the code works if I enter a article id instead of a variable $post_id;

function cron_add_one_minute( $schedules ) {
    $schedules['one_minute'] = array(
        'interval' => 60,
        'display'  => 'One in minute'
    );
    return $schedules;
};
    if(!empty($_POST) && ($_POST['btnaup']) && !wp_next_scheduled( 'update_post' )) {
        wp_schedule_event( time(), 'one_minute', 'update_post');
    }

    if(isset( $_POST['btnaup'])) {
        $post_id = $_POST['id'];
        $b = $_POST['days'];
    }

add_action( 'update_post', 'update_my_post', 10, 1);

function update_my_post( $post_id ){
        $time = current_time('mysql');
 
        wp_update_post( array (
            'ID'            => $post_id, 
            'post_date'     => $time,
            'post_date_gmt' => get_gmt_from_date( $time ),
            'post_modified' => $time,
            'post_modified_gmt' => get_gmt_from_date($time),
        )  );
}





Answer:
Per the docs for wp_schedule_event, the fourth parameter, which you are 't currently using, is $args

Array containing arguments to pass to the hook's callback function. Each value in the array is passed to the callback as an individual parameter.
The array keys are ignored.
Default: array()

This means you should be able to use:
if (!empty($_POST) && ($_POST['btnaup']) && !wp_next_scheduled('update_post')) {
    $data = [
        $_POST['id'],
    ];

    wp_schedule_event(time(), 'one_minute', 'update_post', $data);
}

Your update_my_post function should just work then.
Question: the trait `FromSql` is not implemented for `DateTime`

I'm getting the following error when trying to compile my rust diesel project despite the diesel docs showing that this trait is implemented

the trait bound DateTime<Utc>: FromSql<diesel::sql_types::Timestamptz, Pg> is not satisfied

My schema.rs
pub mod offers {
    diesel::table! {
        offers.offers (id) {
            id -> Int4,
            #[max_length = 255]
            offername -> Varchar,
            #[max_length = 255]
            offertypeid -> Nullable<Varchar>,
            startdate -> Nullable<Timestamptz>,
            enddate -> Nullable<Timestamptz>,
            frequency -> Nullable<Int4>,
            #[max_length = 255]
            createdby -> Nullable<Varchar>,
            createdAt -> Nullable<Timestamptz>
        }
    }
}


Here is my models.rs:
use diesel::prelude::*;
use chrono::{DateTime, Utc};
use crate::schema::offers::offers as offerTable;

#[derive(Queryable, Selectable)]
#[diesel(table_name = offerTable)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct Offer {
    pub id: i32,
    pub enddate: Option<DateTime<Utc>>,
    pub createdAt: Option<DateTime<Utc>>,
    pub createdby: Option<String>,
    pub frequency: Option<i32>,
    pub offername: String,
    pub startdate: Option<DateTime<Utc>> <--- ERROR FOR THIS LINE
}

In the docs for diesel here is shows that this mapping should work and I haven't been able to figure out why it's not working



Answer:
You need to enable the "chrono" feature for the implementation for DateTime<UTC> from the chrono crate to be provided. This is shown as an annotation in the docs and is not enabled by default. You can read more about this feature and others in Diesel's crate feature flags section of the docs.
So your Cargo.toml should contain at least this:
[dependencies]
diesel = { version = "2.1.0", features = ["postgres", "chrono"] }

This goes for Diesel version 1.x as well.
Question: Is there a faster algorithm for max(ctz(x), ctz(y))?

For min(ctz(x), ctz(y)), we can use ctz(x | y) to gain better performance. But what about max(ctz(x), ctz(y))?
ctz represents "count trailing zeros".
C++ version (Compiler Explorer)
#include <algorithm>
#include <bit>
#include <cstdint>

int32_t test2(uint64_t x, uint64_t y) {
    return std::max(std::countr_zero(x), std::countr_zero(y));
}

Rust version (Compiler Explorer)
pub fn test2(x: u64, y: u64) -> u32 {
    x.trailing_zeros().max(y.trailing_zeros())
}



Answer:
These are equivalent:

max(ctz(a),ctz(b))
ctz((a|-a)&(b|-b))
ctz(a)+ctz(b)-ctz(a|b)

The math-identity ctz(a)+ctz(b)-ctz(a|b) requires 6 CPU instructions, parallelizable to 3 steps on a 3-way superscalar CPU:

3× ctz
1× bitwise-or
1× addition
1× subtraction

The bit-mashing ctz((a|-a)&(b|-b)) requires 6 CPU instructions, parallelizable to 4 steps on a 2-way superscalar CPU:

2× negation
2× bitwise-or
1× bitwize-and
1× ctz

The naïve max(ctz(a),ctz(b)) requires 5 CPU instructions, parallelizable to 4 steps on a 2-way superscalar CPU:

2× ctz
1× comparison
1× conditional branch
1× load/move (so that the "output" is always in the same register)

... but note that branch instructions can be very expensive.
If your CPU has a conditional load/move instruction, this reduces to 4 CPU instructions taking 3 super-scalar steps.
If your CPU has a max instruction (e.g. SSE4), this reduces to 3 CPU instructions taking 2 super-scalar steps.
All that said, the opportunities for super-scalar operation depend on which instructions you're trying to put against each other. Typically you get the most by putting different instructions in parallel, since they use different parts of the CPU (all at once). Typically there will be more "add" and "bitwise or" units than "ctz" units, so doing multiple ctz instructions may actually be the limiting factor, especially for the "math-identity" version.
If "compare and branch" is too expensive, you can make a non-branching "max" in 4 CPU instructions. Assuming A and B are positive integers:

C = A-B
subtract the previous carry, plus D, from D itself (D is now either 0 or -1, regardless of whatever value it previously held)
C &= D (C is now min(0, A-B))
A -= C (A' is now max(A,B))
Question: Using Office365 Excel array formulas, how to convert this standard formula?

These two formulas are the same, except the first one is not an array formula and the second one is.  How can the first formula be converted to an array formula?  Getting circular logic when using the array formula.
Standard Formula (works fine, no circular logic):
=LET(a, A2, b, B2, c, C2, d, D1, e, E1,
    dd, IF(a = 1, 0, d),
    ee, IF(a = 1, 0, e),
(b * c + dd * ee ) / (b + dd)  )

Array Formula (circular logic error):
=LET(a, A9:A12, b, B9:B12, c, C9:C12, d, D8:D11, e,E8:E11,
    dd, IF(a = 1, 0, d),
    ee, IF(a = 1, 0, e),
(b * c + dd * ee ) / (b + dd)  )

The formula is a fairly simple weighted average of two sets of numbers.  Trying to convert it to an array formula.  The previous result is used on the following row, except on the first row where there is no previous result.
The difficulty is in how to reference the previous result cell when calculating the current cell.

Data:




Seq
B
C
D




1
100
1.00
-


2
100
3.00
800


3
250
2.00
200


4
400
5.00
300





Answer:
INDEX each array and use SCAN to return the values:
=LET(
    a, A9:A12, 
    b, B9:B12, 
    c, C9:C12, 
    d, D8:D11,
    dd, IF(a = 1, 0, d),
    SCAN(0,a,LAMBDA(z,y,(INDEX(b,y)*INDEX(c,y)+INDEX(dd,y)*z)/(INDEX(b,y)+INDEX(dd,y)))))
Question: Area of each cell covered by polygons

Is there a way/function to calculate the proportion of each raster cell covered by a polygon? The polygons are usually larger than single cells and the landscape I'm working on is pretty big. I'll like to do it without converting the raster into cell-polygons and st_union/st_join, but I'm not sure if it's possible.
The output I'm looking for is a raster with cell values showing the proportion of each cell covered by the polygons layer.


Answer:
Thanks for the comments.
At the end the terra::rasterize() function with the cover = T parameter applied on the polygons layer does exactly what I was looking for... and it's super fast.
I was able to keep it all on the "raster side" and avoid the more intense processing of vectorizing the raster template and doing intersects/spatial joins.
Question: Chain assertions together in kotlin

I have an operation that I want to succeed with two different conditions. For example, if the status code is 501 OR message is not 'FAILED'. Is there a way to have assertions grouped together logically like AND/OR. If assertion 1 passes OR assertion 2 passes, I want my test case to succeed.


Answer:
@cactustictacs suggests "naming" your assertions and then chaining them.
I'll suggest an answer by showing code that validates 4x REST interface inputs that have some complex permutations that allowed / not allowed.  This code is arguably easier to read than a classic if ... else structure.
See how they are evaluated using the when construct.   Perhaps you can take these ideas for your assertions...
val userIdNotNull = userId != null
        && channelType == null
        && primaryMentorId == null
        && primaryClinicianId == null

val userIdAndChannelTypeNotNull = userId != null
        && channelType != null
        && primaryMentorId == null
        && primaryClinicianId == null

val primaryMentorIdNotNull = userId == null
        && channelType == null
        && primaryMentorId != null
        && primaryClinicianId == null

val primaryClinicianIdNotNull = userId == null
        && channelType == null
        && primaryMentorId == null
        && primaryClinicianId != null

val channels = when {
    userIdNotNull -> getChannelsByUserId(userId)
    userIdAndChannelTypeNotNull -> channelRepository.findByMemberIdAndChannelType(userId!!, channelType!!)
        .ifEmpty { throw NotFoundException() }

    primaryMentorIdNotNull -> channelRepository.findByPrimaryMentorId(primaryMentorId)
        .ifEmpty { throw NotFoundException() }

    primaryClinicianIdNotNull -> channelRepository.findByPrimaryClinicianId(primaryClinicianId)
        .ifEmpty { throw NotFoundException() }

    else -> throw InvalidRequestParameterException("This combination of request parameters is not supported")
}