satoshi-2000/llms-suitable huggingface dataset:
Question: How can we stop vuetify 3 v-combobox from adding new items if the validation checks fail?

I have tried using the validation-on, rules props, they are able to validate and give me error messages but the new items are still getting appended to the state. Is there any way to change this behaviour so that every time there is a validation error it don't append the item to the state?
ParentComponent.vue
...
 <MultiSelect
    v-model="form.tags"
    label="Select Tags"
    :items="tags"
    item-title="name"
    item-value="id"
  />
...

MultiselectComponent.vue
<template>
    <v-combobox 
        multiple 
    chips 
        closable-chips 
        clearable 
        :return-object="false"
        variant="outlined"
    />
</template>

What I want
Basically I don't want user to add tags that starts with a number or are all numbers

e.g. 123, 2VueJs, 456890, 68yjkk etc.



Answer:
Validation is used to show error messages to the user and prevent the form from being submitted. But if you remove invalid values immediately, there is no error message and the values are always going to be valid.
So instead of validation, you can just filter the values coming out of the component. Just replace the v-model with the underlying :modelValue and @update:modelValue and pipe the values through a filter:
<v-combobox
  :model-value="values"
  @update:model-value="values = filterInvalid($event)"
  ...
/>

You can also use the filter on the input of :modelValue to filter any invalid values coming in, depending on if there are preset values and how to deal with them if they are invalid.
Here it is in a snippet:


const { createApp, ref } = Vue;
const { createVuetify } = Vuetify
const vuetify = createVuetify()
const app = {
  setup(){
    return {
      values: ref([12, '12n','n']),
      filterInvalid: (inputValues) => inputValues.filter(value => typeof value === 'string' && isNaN(value[0]))
    }
  }

}
createApp(app).use(vuetify).mount('#app')
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/vuetify@3/dist/vuetify.min.css" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main class="pa-8">
    
      <v-combobox
        :model-value="filterInvalid(values)"
        @update:model-value="values = filterInvalid($event)"
        multiple
        chips
        closable-chips
        clearable
        variant="outlined"
      ></v-combobox>
      
      <div>Values: {{values}}</div>
      
      </v-main>
  </v-app>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@3/dist/vuetify.min.js"></script>



Note however that removing values automatically can feel like a bug to users. You might be better off with the validation approach after all.
Question: I tried Simple Jolt transformation but its not working

I want to convert this data using jolt, I tried but it showing null as result
Input :
{
  "employer": [
    {
      "id": "98",
      "place_id": "7871",
      "name": "Iti-ha-cho"
    }
  ]
}

Expected Output :
{
  "id" : "98",
  "place_id" : "7871",
  "name" : "Iti-ha-cho"
}

Jolt Spec I tried but didnt work :
{
  "operation": "shift",
  "spec": {
    "employer": {
      "id": "[&1].&",
      "place_id": "place_id",
      "name": "name"
    }
  }
}



Answer:
While the current issue is due to missing square bracket nesting the spec, you don't need to specify those long stuff, just the following spec will suffice
[
  {
    "operation": "shift",
    "spec": {
      "employer": {
        "*": ""
      }
    }
  }
]

as you only want to extract the sub-content of the employer array.
Question: form with 2 int inputs where one always has to be lower and one always has to higher

I think its's pretty clear in my code what I am trying to do. basically I'm trying to use the max and min parameter from the input to make it so that they can never cross each other. This doesn't work of course, I am using react and am using usestate to set the values whenever the form is submitted and pass these variables into my database fetch. I feel like using 2 states one for the temporary value of the input and one to pass the submitted value to the fetch is not a good way of solving this.
const [ LowestPrice, setLowestPrice ] = useState(0)
const [ HighestPrice, setHighestPrice ] = useState(500)

useEffect(() =>{
const getProps = async () => {
const { data, count, error } = await backbase.from('products_2')
      .select('*', { count: 'exact' })
      .gte('price', LowestPrice)
      .lt('price', HighestPrice)
      .range(indexOfFirstItem, indexOfLastItem - 1)
}}, [LowestPrice, HighestPrice])

const handleSubmit = (e) => {
    e.preventDefault()

    setLowestPrice(document.getElementById("lowest_price")?.value)
    setHighestPrice(document.getElementById("highest_price")?.value)
  }

<form onSubmit={handleSubmit}>
        <label htmlFor="lowest_price">minimum price</label>
        <input
          type="number"
          id="lowest_price"
          defaultValue={LowestPrice}
          min={0}
          max={document.getElementById("highest_price")?.value}
        />
        <label htmlFor="highest_price">maximum price</label>
        <input
          type="number"
          id="highest_price"
          defaultValue={HighestPrice}
          min={document.getElementById("lowest_price")?.value}
          max={500}
        />
        <button type="submit">apply filters</button>
      </form>

I left out unessential parts of the code to make it easier to read. It's the min and max in the form that are the most relevant.


Answer:
Firstly, don't use getElementById to listen to changes. React triggers a re-render on components when their value changes. In order to retain the value, we use useState. Secondly, you can use OnChange to compare between both values in state before deciding whether or not to discard the new value. Try something like this;
const [lowestPrice, setLowestPrice] = useState(0);
const [highestPrice, setHighestPrice] = useState(1);

return (
<form onSubmit={handleSubmit}>
    <label htmlFor="lowest_price">minimum price</label>
    <input
      onChange={e => e.target.value <= highestPrice && setLowestPrice(e.target.value)} value={lowestPrice}
      type="number"
      id="lowest_price"
      defaultValue={lowestPrice}
      value={lowestPrice}
      min={0}
      max={highestPrice}
    />
    <label htmlFor="highest_price">maximum price</label>
    <input
      onChange={e => e.target.value > lowestPrice && setHighestPrice(e.target.value)}
      type="number"
      id="highest_price"
      defaultValue={highestPrice}
      value={highestPrice}
      min={lowestPrice}
      max={500}
    />
    <button type="submit">apply filters</button>
  </form>
)
Question: Postgresql Need a query that gives me all the parents that don't have child with a specific status value

This is the parent table named route




id
start_day
end_day




1
2023/05/01
2023/05/07


2
2023/05/01
2023/05/07


3
2023/05/01
2023/05/07


4
2023/05/01
2023/05/07


5
2023/05/01
2023/05/07




Child table named route_detail




id
route_id
visit_status
point_of_delivery_plant_name
point_of_delivery_plant_number




1
1
5
CROP SOLUTIONS S.A.
563


2
1
5
CROP SOLUTIONS S.A.
563


3
1
5
CROP SOLUTIONS S.A.
563


4
2
0
SAMA S.A.
781


5
3
0
WALTER SAMA HARMS
732


6
4
5
AGROSER S.A.
242


7
4
5
AGROSER S.A.
242


8
5
5
AGROFERTIL S.A
287


9
5
5
AGROFERTIL S.A
287


10
5
5
AGROFERTIL S.A
287




and a third child table named event, for each record route_detail there is 1 event. This is child to route_detail




id
route_detail_id
event_type
event_description




50
1
1
start visit


51
2
2
recurrent form


52
3
3
end visit


53
4
1
start visit


54
5
1
start visit


55
6
1
start visit


56
7
2
recurrent form


57
8
1
start visit


58
9
2
recurrent form


59
10
4
harvest advance




What I'm trying to do is to get all the routes with visit_status = 5 and that don't have events with event_type = 3(end visit)
But I can't manage to get that result
I tried something like this after some research but the queries would still return routes with route_details with the event_type = 3 on them
SELECT r.id,
       r.start_day,
       r.end_day,
       de.point_of_delivery_plant_name,
       de.point_of_delivery_plant_number,
       de.visit_status
FROM route r
JOIN route_detail de ON de.route_id = r.id
WHERE NOT EXISTS (SELECT 1 
                  FROM route ro 
                  JOIN route_detail rd ON rd.route_id = ro.id 
                  JOIN event ev ON ev.route_detail_id = rd.id 
                  WHERE rd.route_id = r.id 
                    AND ev.event_type_id !=7 
                    AND rd.visit_status = '5' 
                    AND rd.id = de.id)
   AND de.visit_status = '5'
GROUP BY 1,2,3,4,5,6
ORDER BY r.id DESC;

This is how my results should look like, since only routes 4 and 5 have visit_status = '5' and their route_details don't have event_type =3
Note: I didn't make the tables




id
start_day
end_day




4
2023/05/01
2023/05/07


5
2023/05/01
2023/05/07





Answer:
If you want to do it with the EXISTS expression, you can use:

one EXISTS to check the existence of route_detail.visit_status = 5
one EXISTS to check the non-existence of event.event_type = 3 when route_detail.visit_status = 5

SELECT r.*
FROM route r
WHERE EXISTS(SELECT 1
             FROM route_detail rd
             WHERE r.id = rd.route_id
               AND rd.visit_status = 5 )
  AND NOT EXISTS(SELECT 1 
                 FROM       route_detail rd
                 INNER JOIN "event"      e
                         ON rd.id = e.route_detail_id
                 WHERE r.id = rd.route_id
                   AND e.event_type = 3)

Output:




id
start_day
end_day




4
2023-05-01T00:00:00.000Z
2023-05-07T00:00:00.000Z


5
2023-05-01T00:00:00.000Z
2023-05-07T00:00:00.000Z




Check the demo here.
Question: Sum cells by colors based on other colum cells

I wanna sum cells that have the same color. I know there are some VBA functions to do that. But my problem is kinda specific. I want to sum cells values from a single column, based on cells colors on another column.
I add an example and the code I used. I got the "#VALUE" error on the line where I try to access the Interior property.

Function SumByColor(CellColor As Range, rRange As Range)
 Dim cSum As Double
 Dim ColIndex As Integer
 Dim compatedCell As Range  
 Debug.Print ("sumbycolor called")

 ColIndex = CellColor.Interior.ColorIndex

 For Each cl In rRange
  comparedCell = Worksheets("HA").Cells(cl.Row, 1)
  Debug.Print (comparedCell.Interior.ColorIndex) #nothing printed

  If comparedCell.Interior.ColorIndex = ColIndex Then
   cSum = WorksheetFunction.Sum(cl, cSum)
  End If
  Next cl

 SumByColor = cSum

End Function

Thx for your help.


Answer:
You should dim all your variables.
  Dim cl As Range, comparedCell As Range
  For Each cl In rRange
    Set comparedCell = Worksheets("HA").Cells(cl.Row, 1)
    Debug.Print (comparedCell.Interior.ColorIndex) 'nothing printed

    If comparedCell.Interior.ColorIndex = ColIndex Then
         cSum = WorksheetFunction.Sum(cl, cSum)
    End If
  Next cl

As comparedCell is a Range-object you have to use Set.
Question: Nest.js empty Body for form data

I have a simple controller, in this controller I have this endpoint
@Post('/temp')
async asdf(
  @Body() form: Record<string, string>,
  @Res({ passthrough: true }) response: Response,
) {
  this.logger.debug(JSON.stringify(form));
  await response.json({ ok: true, form: JSON.stringify(form) });
}

When I try to POST some form data on it, using cURL or the browser, the object form is empty.
Example:
curl -X POST http://localhost:4000/mycontroller/temp -H "Content-Type: application/x-www-form-urlencoded" -d "param1=value1&param2=value2"

Results in

{"ok":true,"form":"{}"}

Other controllers work; I can't see any difference between my controller and the endpoint to others.
What I'm doing wrong or missing?


Answer:
If you're using form data you need to implement a form data parser, like busboy or multer. Nest integrates with multer and express already via the FileInterceptor and its variants. This will force multer to parse the request. If you don't use any files, just the form data format, I believe there is a NoFileInterceptor or similar.

Looks like there is no NoFileInterceptor. You could use AnyFileInterceptor instead and ignore the req.files, just be aware it could end up having your server taken down if a really nasty set of files comes in for multer to parse
Question: How to construct a graph using a list of tuples in python in networkX?

I am trying to make a graph from a list of tuples stored in a variable. I found G.add_edges_from(e) for making graph using list of tuples. but the problem is that this does not work and when i try to for example print the graph it returns None. I appreciate answers that solve my problem. I use the code below to make the graph:
import networkx as nx

e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
g1 = G.add_edges_from(e)
print(g1)


Update:
I testes this code but again give None when trying to print:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
    graph_list.append(nx.Graph().add_edges_from(i))

print(graph_list[0].nodes)




Answer:
Let's break it down shall we?
You assigned a list of edges in e, then you made a graph with G.
However, your issue is you're trying to assign g1 to what the method add_edges_from returns (which is None).
What you actually want is something like this:
import networkx as nx

e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
G.add_edges_from(e)
print(G)

Since the add_edges_from method returns None it is working as intended, you should try printing your original graph instead. I hope this helps and clarifies things for you!
Edit:
If you insist on just using the list of tuples, you can just do away with variables. Use lists to store graph objects instead, keep storing them in a loop as such:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
    G = nx.Graph()
    G.add_edges_from(i)
    graph_list.append(G)

print(graph_list[0].nodes)
print(graph_list[1].nodes)

Then you can use indices to get each specific graph you make (which would be stored separately in the list)
Or you might want to start dumping each graph in a json file ([answered here] (Method to export networkx graph to json graph file?))
Which can solve your RAM issue
Question: Why is strtol() returning 0x7fffffff instead of the expected 0xAABBCCDD?

// msvc 17.3.5
// sizeof (long) : 4
#include <stdlib.h>
int main(){
    long i = 0xAABBCCDD;// 0x AABBCCDD in debugger window

    char number[] = "AABBCCDD EEFF";
    char* p;
    long var = strtol ( number, &p, 16 );// 0x 7FFF FFFF
    perror ( "?:" ); // ?:: Result too large
}

I tried char number[] = "AABBCC EEFF"; and it works fine.
I expect 0xAABBCCDD inside var instead 0x7fffffff.
What is wrong?


Answer:
From the C Standard (7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions)

8 The strtol, strtoll, strtoul, and strtoull functions
return the converted value, if any. If no conversion could be
performed, zero is returned. If the correct value is outside the range
of representable values, LONG_MIN, LONG_MAX, LLONG_MIN,
LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of
the macro ERANGE is stored in errno.

The positive hexadecimal constant 0xAABBCCDD can not be represented in an object of the signed type long int provided that sizeof( long int ) is equal to 4.
For example try this demonstration program
#include <stddef.h>
#include <stdio.h>

int main( void )
{
    printf( "%#X\n", LONG_MAX );
}

The program output is
0X7FFFFFFF

Note: as in this case sizeof( long ) is equal to sizeof( unsigned int ) and the value is representable in an object of the type unsigned int there is used the conversion specifier X. Otherwise you need to include header <inttypes.h> and to use a macro as for example PRIX32.
As you can see LONG_MAX (the maximum positive value that can be stored in an object of the type long int)  is less than the positive hexadecimal constant 0xAABBCCDD.
Instead of using the function strtol use function strtoul
unsigned long var = strtoul ( number, &p, 16 );

Or if you want to deal with signed integers then use function strtoll.
Question: Is this a race condition in go

func main() {
    m := map[string]int{
        "foo": 42,
        "bar": 1337,
    }

    go func() {
        time.Sleep(1 * time.Second)
        tmp := map[string]int{
            "foo": 44,
            "bar": 1339,
        }

        m = tmp
    }()

    for {
        val := m["foo"]
        fmt.Println(val)
    }
}

I saw this in many packages.
Why this is not considered as a race condition?
go run -race . giving no error.


Answer:
As pointed out by @Volker, this is a data race. And since there is only one write, it's hard to be detected. Here is a modified demo to make it easy to trigger the data race error:
package main

import (
    "fmt"
    "time"
)

func main() {
    m := map[string]int{
        "foo": 42,
        "bar": 1337,
    }

    done := make(chan any)

    go func() {
        for i := 0; i < 100; i++ {
            time.Sleep(time.Microsecond)
            tmp := map[string]int{
                "foo": 44,
                "bar": 1339,
            }

            m = tmp
        }

        close(done)
    }()

    for {
        select {
        case <-done:
            return
        default:
            val := m["foo"]
            fmt.Println(val)
        }
    }
}
Question: Condition to filter records with "in" and "and" operators





ID
name
isSearchable




1
foo
true


2
bar
true


3
zar
false




I've got some ids and I need to filter records where they have isSearchable = true.
This query give as result ID = 1 because is searchable, but I would to apply the filter isSearchable to the entire result, not row-by-row.
SELECT *
FROM my_table
WHERE id IN (1, 3)
  AND isSearchable = true

So in this case I'm expecting no-results because both records should be in first isSearchable and after that, filter the ids.
I've tried experimenting with sub-query etc but the in operator (or the or operator) but I'm not able to accomplish the result.
Maybe is something really simple, but I've no ideas on how to solve.
Thanks for your help.


Answer:
One approach using a window function:
SELECT ID 
FROM (SELECT ID,
             MIN(isSearchable::INT) OVER() AS minSearchable
      FROM my_table
      WHERE id IN (1,3)) cte 
WHERE minSearchable = 1

Check the demo here.
Question: How can I create a dynamic list in Terraform that combines a list of strings with a list of maps?

Merge list with another list of map in terraform
We have a list listA and a list of map, mapA as below
listA = ["cluster-0","cluster-1"]


mapA = [
{
  auto_upgrade       = false
  disk_size_gb       = 100
  disk_type          = "pd-standard"
  node_pool_labels            = {
    agentpool = "np-1"
  }
},
{
  auto_upgrade       = false
  disk_size_gb       = 50
  disk_type          = "pd-balanced"
  node_pool_labels            = {
    agentpool = "np-2"
  }
},
{
 auto_upgrade                = false
 disk_size_gb                = 100
 disk_type                   = "pd-standard"
 node_pool_labels            = {
    agentpool = "np-3"
 }
}
]


I am trying to create a new list which should look like
listB = [
"cluster-0" = [{
  auto_upgrade       = false
  disk_size_gb       = 100
  disk_type          = "pd-standard"
  node_pool_labels   = {
      agentpool = "np-1"
   }
 },
 {
  auto_upgrade       = false
  disk_size_gb       = 50
  disk_type          = "pd-balanced"
  node_pool_labels   = {
      agentpool = "np-2"
   }
 },
 {
  auto_upgrade                = false
  disk_size_gb                = 100
  disk_type                   = "pd-standard"
  node_pool_labels            = {
      agentpool = "np-3"
  }
}], 

"cluster-1"= [{
  auto_upgrade       = false
  disk_size_gb       = 100
  disk_type          = "pd-standard"
  node_pool_labels   = {
      agentpool = "np-1"
   }
 },
 {
  auto_upgrade       = false
  disk_size_gb       = 50
  disk_type          = "pd-balanced"
  node_pool_labels   = {
      agentpool = "np-2"
   }
 },
 {
  auto_upgrade                = false
  disk_size_gb                = 100
  disk_type                   = "pd-standard"
  node_pool_labels            = {
      agentpool = "np-3"
  }
}]
] 

I have tried zipmap which works when listA has two elements and mapA has got two elements like only np-1, np-2 but fails when we add np-3. Trying to make this dynamic listB.


Answer:
You can use:
listB = [{for idx, value in local.listA: value => local.mapA }]

so iterate over listA to create a new list where the elements are a dict of which the key is the original element in listA, and the value mapA.
Question: UA_Client_Service_read only yields empty responses

I am trying to create a small program in C which will poll a frame of data over a opc/ua connection using the open62541 library and the forward it to a kafka server.
Everything works fine when fetching the values from the nodes separately but I would like to use a UA_ReadRequest for that. The problem is that I am only receiving empty responses.
The opc/ua server is coded with in python using the freeopc package.
This is the function that tries tu use a UA_ReadResponse to fetch a several values for specified nodeIDs:
void retrieveOPCData(void)
{
    UA_ReadRequest request;
    UA_ReadRequest_init(&request);
    UA_ReadValueId ids[nodeCount];
    
    for (int i = 0; i < nodeCount; i++)
    {
        UA_ReadValueId_init(&ids[i]);
        ids[i].attributeId = UA_ATTRIBUTEID_VALUE;
        ids[i].nodeId = nodesToRead[i];
    }

    request.nodesToRead = ids;

    for (int i = 0; i < nodeCount; i++)
    {
        UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "ID%i: %s, %i", i,
            request.nodesToRead[i].nodeId.identifier.string.data,
            request.nodesToRead[i].nodeId.namespaceIndex);
    }

    UA_ReadResponse response = UA_Client_Service_read(client, request);

    UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Status: %i",
        response.responseHeader.serviceResult);
    UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Responses: %li", response.resultsSize);
}

The result value is UA_STATUSCODE_GOOD but the number of responses is 0. It works fine when fetching the values one after the other like this:
void readNodeAtIndex(int index)
{
    if (index >= nodeCount)
    {
        UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Index out of Range");
        return;
    }

    UA_Variant variant;
    UA_Variant_init(&variant);

    const UA_NodeId nodeId = nodesToRead[index];

    UA_StatusCode retval = UA_Client_readValueAttribute(client, nodeId, &variant);

    if (retval == UA_STATUSCODE_GOOD && UA_Variant_hasScalarType(&variant,
        &UA_TYPES[UA_TYPES_DOUBLE]))
    {
        UA_Double value = *(UA_Double*)variant.data;

        UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Double-Value: %f", value);
    }
    else if (retval == UA_STATUSCODE_GOOD && UA_Variant_hasScalarType(&variant,
        &UA_TYPES[UA_TYPES_BOOLEAN]))
    {
        UA_Boolean value = *(UA_Boolean*)variant.data;

        UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Boolean-Value: %i", value);
    }
    

    UA_Variant_clear(&variant);
}

The opc/ua server is setup like this:
server = Server()
space_url = "opc.tcp://localhost:61032"
server.set_endpoint(space_url)
server.set_security_policy([ua.SecurityPolicyType.NoSecurity])
node = server.get_objects_node()



Answer:
You need to set nodesToReadSize:
    UA_ReadRequest request;
    UA_ReadRequest_init(&request);
    UA_ReadValueId ids[nodeCount];
    
    for (int i = 0; i < nodeCount; i++)
    {
        UA_ReadValueId_init(&ids[i]);
        ids[i].attributeId = UA_ATTRIBUTEID_VALUE;
        ids[i].nodeId = nodesToRead[i];
    }
    request.nodesToReadSize = nodeCount;
    request.nodesToRead = ids;