satoshi-2000/llms-suitable huggingface dataset:
Question: How to pass SQLX connection - a `&mut Trait` as a fn parameter in Rust

I need to generalize functions to pass an Executor trait for SQLX code. In the code below with a concrete &mut SqliteConnection parameter, main can call process, or it can call process_twice which calls process 2x times.  All sqlx functions require arg type E: Executor.
I need to make my code generic so that conn: &mut SqliteConnection arg is also written with some generic, but so i can use it more than once.
Inside Sqlx, multiple structs implement Executor trait on a mutable reference, e.g.
impl<'c> Executor<'c> for &'c mut SqliteConnection {...}

I was able to convert a SINGLE call (the fn process), but not the  fn process_twice - because executor is not copyable.
async fn process<'a, E>(conn: E) -> anyhow::Result<()>
where E: sqlx::Executor<'a, Database = sqlx::Sqlite> {...}

Full example
// [dependencies]
// anyhow = "1.0"
// futures = "0.3"
// sqlx = { version = "0.6", features = [ "sqlite", "runtime-tokio-native-tls"] }
// tokio = { version = "1.28.2", features = ["macros"] }
//
//  //// TO RUN, must set env var:
// DATABASE_URL='sqlite::memory:' cargo run

use futures::TryStreamExt;
use sqlx::SqliteConnection;
use sqlx::{query, Connection};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut conn = SqliteConnection::connect("sqlite::memory:").await?;
    process(&mut conn).await?;
    process_twice(&mut conn).await?;
    Ok(())
}

async fn process(conn: &mut SqliteConnection) -> anyhow::Result<()> {
    let sql = query!("SELECT name FROM sqlite_master");
    let mut rows = sql.fetch(conn);
    while let Some(row) = rows.try_next().await? {
        println!("{row:?}")
    }
    Ok(())
}

async fn process_twice(conn: &mut SqliteConnection) -> anyhow::Result<()> {
    process(conn).await?;
    process(conn).await?;
    Ok(())
}

Similar questions: this


Answer:
The trick is to not parametrize the whole E but just the type behind the reference:
async fn process_twice<T>(conn: &mut T) -> anyhow::Result<()>
where
    for<'e> &'e mut T: Executor<'e, Database = Sqlite>,
{
    process(&mut *conn).await?;
    process(conn).await
}

That way you can still reborrow the reference. That does mean that you can't take Pool<DB> any more because it only implements Executor for &Pool but should work for your usecase.
Question: Issue with loading jquery after bootstrap

I tried to research before asking here, but I coun't find any answers. Just for context, I'm using old version of bootstrap v2.0.2. I doubled checked if my paths are correct, and they are.

This is the order of imported scripts that produce the errors above. If I load bootstrap.min.js first, I will get a different error.
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
   <script src="lib/jquery/jquery-3.7.0.min.js"></script>
   <script src="lib/bootstrap/js/bootstrap.min.js"></script>
        
   <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css">
   <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-responsive.min.css">
   <link rel="stylesheet" href="css/app.css">

   <script src="lib/angular/angular.min.js"></script> 
   <script src="js/app.js"></script>
</head>

I've tried to import bootstrap.min.js first, but this the error message I get, and I'm not sure why.
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
   <script src="lib/bootstrap/js/bootstrap.min.js"></script>
   <script src="lib/jquery/jquery-3.7.0.min.js"></script>
        
   <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css">
   <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-responsive.min.css">
   <link rel="stylesheet" href="css/app.css">

   <script src="lib/angular/angular.min.js"></script> 
   <script src="js/app.js"></script>
</head>

I expected it that this small change would resolve the issue, but it didn't.



Answer:
You cannot use jQuery versions starting with 1.9 with Bootstrap 2.0.2.
jQuery 1.8.3 does work as shown below (note that jQuery must still be loaded before Bootstrap's JavaScript):


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js" integrity="sha512-J9QfbPuFlqGD2CYVCa6zn8/7PEgZnGpM5qtFOBZgwujjDnG5w5Fjx46YzqvIh/ORstcj7luStvvIHkisQi5SKw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.0.2/bootstrap.min.js" integrity="sha512-jv0RCzX/cFYIF5KkvheT4Xk06YMyEmYAJ8mxZ0pgzwHMgIdT/KGedWD2dK2modKDyaK6DSDwh6ptzTHtfJ0Nng==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.0/css/bootstrap-responsive.min.css" integrity="sha512-c4E36NNKxeFBnGTk/nFCssF4B7gXdZ9hqBnR0fec+DiZ7EnCB2RA42O8HPdgKHFnseb4s6ieQtmT8iksW+QfWw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
Question: Finding first empty cell in a row problem

I would like to clear everything in each sheet starting from the first empty cell in the 10th row (Microsoft Excel) but .End property skip the empty cell between filled ones.
I tried such code:
Sub clearRange()
    
    Dim ws As Worksheet
    Dim lastColumn As Long, i As Long
    
    For i = 2 To Worksheets.Count - 1
        Set ws = Worksheets(i)
        lastColumn = ws.Cells(10, ws.Columns.Count).End(xlToLeft).Column
        ws.Range(ws.Cells(10, lastColumn + 1), ws.Range("CZ200000")).ClearContents
    Next i
    
End Sub

Cell D10 is skipped:
Sheet screenshot
Thank you for help in advance.


Answer:
The statement
lastColumn = ws.Cells(10, ws.Columns.Count).End(xlToLeft).Column

will take you to column J as the last column in your picture (lastColumn = 10), NOT to column D.
To find the first empty cell, start in column A and use end-right, if A10:B10 are both non-empty. If either can be empty, you'll have to address them individually.
Sub clearRange()
    Dim ws As Worksheet
    Dim lastColumn As Long, i As Long
    
    For i = 2 To Worksheets.Count - 1
        Set ws = Worksheets(i)
        lastColumn = ws.Cells(10, 1).End(xlToRight).Column + 1  ' Do this
        ws.Range(ws.Cells(10, lastColumn + 1), ws.Range("CZ200000")).ClearContents
    Next i
    
End Sub

If this does or doesn't work for you, let us know the result.
And in future requests, please include a table we can copy. We can't copy a screenshot to a worksheet.
Question: Execution failed while running a Kotlin module in Android Studio

I am getting following error in Build Output when running a Kotlin module :-
Execution failed for task ':Test:compileKotlin'.
> 'compileJava' task (current target is 1.7) and 'compileKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.
Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --scan to get full insights.

The build.gradle file for this module has the following code:-
plugins {
    id 'java-library'
    id 'org.jetbrains.kotlin.jvm'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_7
    targetCompatibility = JavaVersion.VERSION_1_7
}

Kindly help me find the error and its resolution.


Answer:
try to make java version 17 not 1.7 like this:
plugins {
id 'java-library'
id 'org.jetbrains.kotlin.jvm'
}

java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
Question: How to pass a div ID to a PHP function using jQuery AJAX?

PHP Post doesn't receive jQuery ajax post value
I have created an ajax POST with jQuery to obtain the ID of a div and pass it to a PHP function. The function of php is in a folder phpFunction taht contains the file phpFunc.php in the same root of index.php. The post request is:
$(document).ready(function() {
            $('.openModal').click(function() {
                var divId = $(this).attr('id');
                // Invia l'ID al server tramite richiesta AJAX
                $.ajax({
                    type: 'POST',
                    url: 'http://localhost/icollegati/phpFunction/phpFunc.php',
                    data: {divId: divId},
                    success: function(response) {
                        // Gestisci la risposta del server
                        console.log("Risposta",response);
                    }
                });
            });
        });

the PHP function is:
function FetchIdNumber(){
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verifica se il parametro "divId" è stato inviato tramite POST
    if (isset($_POST['divId'])) {
        $id = $_POST['divId'];
        echo "ID: " . $id;
        return $id;
    }
  }
};

Thanks in adavance for the help.


Answer:
you need to call the FetchIdNumber function in your PHP code.
function FetchIdNumber(){
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Verifica se il parametro "divId" è stato inviato tramite POST
        if (isset($_POST['divId'])) {
            $id = $_POST['divId'];
            echo "ID: " . $id;
            return $id;
        }
    }
}

// Call the function
FetchIdNumber();

Make sure to place the function call FetchIdNumber(); after the function definition.
Additionally, please ensure that the path to your PHP file is correct. In your AJAX code, you have specified the URL as http://localhost/icollegati/phpFunction/phpFunc.php. Make sure that this path is accurate and matches the actual location of the PHP file on your server.
Question: Numpy interval of indices around max value on the last dimension

I have an array arr in which I would like to zero the interval (over the last dim) around every max value.
Here's what I'm generally trying to do (this code doesn't work):
assume that interval_size is some positive odd integer.
argmax = np.argmax(arr, axis=-1)

half_interval = (interval_size - 1) // 2  # assume the interval is of odd size
left_index = argmax - half_interval
right_index = argmax + half_interval
# fix overflow
left_index[left_index < 0] = 0
right_index[right_index >= arr.shape[-1]] = arr.shape[-1] - 1

# this is just illustrative and doesn't work:
arr[left_index:right_index] = 0  # zero the interval in-place



Answer:
Given that the intervals could be different sizes, I'd go for boolean indexing:
import numpy as np

arr = np.random.randint(10, size=(8, 8))
half_interval = 2

# Use keepdims=True for easy broadcasting
argmax = arr.argmax(axis=-1, keepdims=True)

# "Normal" indices for the last axis
idx = np.arange(arr.shape[-1])

# True when "normal" index is between
# [argmax - half_interval, argmax + half_interval]
mask = (argmax - half_interval <= idx) & (idx <= argmax + half_interval)

arr[mask] = 0
# or out = np.where(mask, 0, arr) if you don't want to modify arr

Results:
>>> arr
array([[6, 8, 5, 4, 6, 9, 3, 6],
       [9, 4, 9, 3, 9, 0, 3, 6],
       [7, 9, 7, 1, 0, 3, 0, 0],
       [9, 9, 4, 8, 3, 8, 3, 2],
       [9, 7, 6, 9, 2, 0, 9, 6],
       [1, 7, 9, 7, 6, 2, 9, 4],
       [8, 0, 8, 9, 6, 5, 0, 9],
       [2, 0, 9, 5, 9, 0, 2, 4]])
>>> argmax
array([[5],
       [0],
       [1],
       [0],
       [0],
       [2],
       [3],
       [2]], dtype=int64)
>>> mask
array([[False, False, False,  True,  True,  True,  True,  True],
       [ True,  True,  True, False, False, False, False, False],
       [ True,  True,  True,  True, False, False, False, False],
       [ True,  True,  True, False, False, False, False, False],
       [ True,  True,  True, False, False, False, False, False],
       [ True,  True,  True,  True,  True, False, False, False],
       [False,  True,  True,  True,  True,  True, False, False],
       [ True,  True,  True,  True,  True, False, False, False]])
>>> out
array([[6, 8, 5, 0, 0, 0, 0, 0],
       [0, 0, 0, 3, 9, 0, 3, 6],
       [0, 0, 0, 0, 0, 3, 0, 0],
       [0, 0, 0, 8, 3, 8, 3, 2],
       [0, 0, 0, 9, 2, 0, 9, 6],
       [0, 0, 0, 0, 0, 2, 9, 4],
       [8, 0, 0, 0, 0, 0, 0, 9],
       [0, 0, 0, 0, 0, 0, 2, 4]])

The above should work for arrays with more than 2 axes as well due to broadcasting. But only because you argmax over the final axis.
Question: Converting np.int16 to torch.ShortTensor

I have many NumPy arrays of dtype np.int16 that I need to convert to torch.Tensor within a torch.utils.data.Dataset.  This np.int16 ideally gets converted to a torch.ShortTensor of size torch.int16 (docs).
torch.from_numpy(array) will convert the data to torch.float64, which takes up 4X more memory than torch.int16 (64 bits vs 16 bits).  I have a LOT of data, so I care about this.
How can I convert a numpy array to a torch.Tensor minimizing memory?


Answer:
Converting a numpy array to torch tensor:
array = np.ones((1000, 1000), dtype=np.int16)
print("NP Array size: {}".format(array.nbytes))
t = torch.as_tensor(array) # as_tensor avoids copying of array 
print("Torch tensor type: {}".format(t.dtype))
print("Torch tensor size: {}".format(t.storage().nbytes()))

NP Array size: 2000000
Torch tensor type: torch.int16
Torch tensor size: 2000000
Question: In sveltekit, what's the convention for splitting client side code between route files?

Both +page.js/ts and the <script><script/> tags within +page.svelte files are for processing client side code.
What's the typical convention for choosing between these 2 files?


Answer:
The question has been clearly answered in the Documentation. The separate file is for loading and constructing data that is required by your route, the script tag is for DOM manipulation and client side logic.
That is the convention as per the docs but you are free to use both methods as per your preference but +page.server.js/ts is strictly  for server side logic like authentication and database calls.
Question: How to send a widget object created later to callback in Tk?

I am new to Perl Tk.
I have option menu.  In its callback, I want to pass a table object which is created later. As per the selection of the option, I want to render specific data into the table.
Since my optionmenu is created before, how can I send the table object to it?
In the code, I have commented it as 'HOW TO PASS ?
use Tk;
use Tk::Table;
use Tk::NoteBook;
use Tk::Optionmenu;

my $data = { 'Jan' =>  { 'id' => 1, 'product' => 'new'} , 'Feb' => {'id'=>2, 
'product'=> 'latest'} }; 

&tk_gui(); 

sub tk_gui {

my $mw = MainWindow->new;
$mw->geometry("500x500");
my $f = $mw->Frame()->pack(-side=>'top');
my ($var, $tvar);
my $opt = $f->Optionmenu(
-options => [[jan =>1], [feb =>2]],
-command => sub { 
        my @nums = @_;
        #HOW TO PASS ?
        &show_table_data($nums[0], $table)

        
    },
-variable => \$var,
-textvariable => \$tvar,
)->pack(-side => 'left', -anchor => 'n',);  

my $f2 = $mw->Frame()->pack(-side=>'bottom');
my $table = $f2->Table( -columns => 2);
my @col = qw(id product);

foreach my $c (0 .. 1) {
if ($c) {
    my $t = $table->Label(-text => 'product'); 
    $table->put(0, $c, $t); 
} else {
    my $t = $table->Label(-text => 'id'); 
    $table->put(0, $c, $t); 

 }

}

$table->pack();

MainLoop;

}

sub show_table_data {
    my $num = shift;
    my $table = shift;
}



Answer:

Since my optionmenu is created before, how can I send the table object to it?

Just declare the $table variable before it is used in the callback. Even if the variable has not been defined when the callback is compiled, it will be defined when the callback is called at runtime. Example:
use feature qw(say);
use strict;
use warnings;
use Tk;
use Tk::Table;
use Tk::NoteBook;
use Tk::Optionmenu;

{    
    tk_gui(); 
}

sub tk_gui {
    my $mw = MainWindow->new;
    $mw->geometry("500x500");
    my $f = $mw->Frame()->pack(-side=>'top');
    my ($var, $tvar);
    my $table;  # <-- declare the variable here..
    my $opt = $f->Optionmenu(
        -options => [[jan =>1], [feb =>2]],
        -command => sub { 
            my @nums = @_;
            show_table_data($nums[0], $table);                
        },
        -variable => \$var,
        -textvariable => \$tvar,
    )->pack(-side => 'left', -anchor => 'n',);  

    my $f2 = $mw->Frame()->pack(-side=>'bottom');
    $table = $f2->Table( -columns => 2);

    foreach my $c (0 .. 1) {
        if ($c) {
            my $t = $table->Label(-text => 'product'); 
            $table->put(0, $c, $t); 
        } else {
            my $t = $table->Label(-text => 'id'); 
            $table->put(0, $c, $t); 

        }
    }
    $table->pack();
    MainLoop;
}

sub show_table_data {
    my $num = shift;
    my $table = shift;
    return if !defined $table;
    say "Num = $num";
    say "table = $table";
}
Question: How do I disable bpython colored output?

bpython by default has a really nice blue theme, but it doesn't go well with light backgrounds. How can I disable its colour output and have it give just plain black (on Arch Linux)?


Answer:
You could create a theme that only uses black as an output color. That might look like:
[syntax]
keyword = k
name = k
comment = k
string = k
error = k
number = K
operator = K
punctuation = k
token = K
paren = K

[interface]
background = d
output = k
main = k
prompt = k
prompt_more = k
right_arrow_suggestion = K

This is based on the default theme, replacing all the colors with k (for normal black) or K (for bold black).
Save this in ~/.config/bpython/light.theme and then set color_scheme = light in ~/.config/bpython/config.
Question: Remove everything in brackets at the end

I'd like to removing everything that is is brackets () if (and only if) they are at the end and not do match the following pattern \(\d{4}\p{Pd}\d{4}\) *. This pattern is nothing more than date range in brackets, eg. (1920-2988).
For instance, I'd like to match/capture (for removing, ie. string.replaceAll(my_regex_here, "")):

foo bar (blah)

foo bar (blah) blah (blah)


I don't like to match:

some (blah) data
some date following (1920-1921).

I have the following regex: \s*(.+?)\s*$. It tends to match too much:

some data (..) match (match)
some data (1920-1977)



Answer:
Use negative look ahead to avoid date ranges, then actually match it using [^()]+?:
\s*\(                  # Match 0+ spaces, a '(',
(?!\d{4}\p{Pd}\d{4}\)) # which is not followed by a date range and a ')',
[^()]+                 # 1+ non-parenthesis characters and
\)\s*$                 # ')' then 0+ spaces right before the end of line.

Try it on regex101.com.
The above regex will not match:
parentheses with no content ()
years with more than 4 digits (1234-56789)
or less than 4 (123-4567)
nested ((brackets))
mismatched (brackets
Question: TrackBar: no Scroll events in the list

I replaced my TrackBar with another TrackBar but when I look for the Scroll event of the new TrackBar I can't find it.
Here is the cole of the old TrackBar:
private void TrackBar_Scroll(object sender, ScrollEventArgs e)

How can I create the Scroll event for the new TrackBar, as it doesn't exist in the event list?


Answer:
Looking at the code of the HZH_Controls in their Github, it would appear you need to handle the ValueChanged event.
/// <summary>
/// Occurs when [value changed].
/// </summary>
[Description("值改变事件"), Category("自定义")]
public event EventHandler ValueChanged;

Other parts of the code suggest that this event is raised Scrollbar is moved
Question: "instagram api" business discovery api on python return 'Invalid OAuth access token - Cannot parse access token' error

I'm writing python code to use instagram graph api/business discovery to get data.
But I get "Invalid OAuth access token" error but I could not figure out how to solve this problam, please enlighten me.
Following code works fine on Graph Api Explorer
IgUserId?fields=business_discovery.username(bluebottle){followers_count,media_count,name}

But when I operate following code on Python file in Jupyter lab
import requests
import pandas as pd
pd.set_option('display.max_rows', None)

# information
business_account_id = "same as IgUserId"
token = "one that generated on Graph Api Explorer"
fields = "followers_count,media_count,name"
version = "v17.0"
username = "bluebottle"

def user_info(version, igUserId,token,username,fields):
    request_url = "https://graph.facebook.com/{version}/{igUserId}?fields={fields}&access_token={access-token}"
    response = requests.get(request_url)
    return response.json()

print(user_info(business_account_id,token,username,fields,version))

I get following error

{'error': {'message': 'Invalid OAuth access token - Cannot parse access token', 'type': 'OAuthException', 'code': 190, 'fbtrace_id': 'Just for case I'm deleteing this bit'}}

To avoid my misunderstanding to confuse anybody, following is picture of Graph Api Explorer where I got Access Token which I just copy and pasted from top black shadowed bit.



Answer:
I am not a Python guy, but just to help you I modified your Python script and while doing that, I saw many issues with your script. Use the below script which I tested with my IG User ID and access_token and is working perfectly fine.
import requests
import pandas as pd
pd.set_option('display.max_rows', None)

# information
business_account_id = "YOUR_IG_USER_ID"
access_token = "YOUR_ACCESS_TOKEN"
fields = "followers_count,media_count,name"
version = "v17.0"
username = "bluebottle"

def user_info(version, igUserId,access_token,username,fields):
    request_url = f"https://graph.facebook.com/{version}/{igUserId}?fields=business_discovery.username({username}){{{fields}}}&access_token={access_token}"
    print(request_url);
    response = requests.get(request_url)
    return response.json()

print(user_info(version,business_account_id,access_token,username,fields))

Output:-
{'business_discovery': {'followers_count': 442462, 'media_count': 2076, 'name': 'Blue Bottle Coffee', 'id': '17841401441775531'}, 'id': '17841448XXXXX'}

I used Python 3.10.6 to test this script.
Hope this helps.
Question: Renaming dataframe columns via User Defined Function via Pandas

i'm trying to rename dataframe columns through User Defined Function without success.
In particular it seems that doesn't exist "rename" method when called inside a UDF.
Following an example to better explain my problem:
import pandas as pd`

data = {'Age': [21, 19, 20, 18,80,90],'Stream': [88, 65,99, 765,65,55],'Percentage': [88, 92, 95, 70,55,47]}

df = pd.DataFrame(data, columns=['Age', 'Stream', 'Percentage'])

print("Given Dataframe :n", df)

def modname(frame):


    frame=frame.rename(columns={'Age':'aa','Stream':'bb','Percentage':'cc'})
    
    return frame

df=df.apply(modname)

print(df)

`
I greatly appreciate your help
i tried the same code without UDF and it works


Answer:
Instead of doing:
df=df.apply(modname)

You should do:
df = modname(df)
Question: How to create comment block in visual studio fast?

In Eclipse I can just type /* and enter, and it would form a perfect comment block for complex comments above the code:
/*
 *
 */

How to do the same or similar in Visual Studio?


Answer:
What language? I'm going to assume C++.
Tools > Options > Text Editor > C/C++ > Advanced > Brace Completion > Complete Multiline Comments > True
This setting will do exactly what you describe. Typing /* will auto-complete the */ and any new line entered after /* will auto-insert a new * at the beginning of the line.
Alternatively:

Download and install Visual Assist: https://www.wholetomato.com/
Highlight code to be commented.
Shift + 8 or * on the keypad.
Profit.