satoshi-2000/llms-suitable huggingface dataset:
Question: sed doesn't replace a string when this is at the end of the line

Why this works
sed -n '242p' /usr/local/lib/python3.6/site-packages/keras/models.py

        model_config = json.loads(model_config.decode('utf-8'))


sed -i "242s/.decode('utf-8')//" /usr/local/lib/python3.6/site-packages/keras/models.py

sed -n '242p' /usr/local/lib/python3.6/site-packages/keras/models.py
        model_config = json.loads(model_config)


and this doesn´t
sed -n '3328p' /usr/local/lib/python3.6/site-packages/keras/engine/topology.py
        original_keras_version = f.attrs['keras_version'].decode('utf8')

sed -i "3328s/.decode('utf-8')//"  /usr/local/lib/python3.6/site-packages/keras/engine/topology.py

sed -n '3328p' /usr/local/lib/python3.6/site-packages/keras/engine/topology.py
        original_keras_version = f.attrs['keras_version'].decode('utf8')

Why I cannot delete the second .decode('utf8'). It is because it is at the end of the string.
I could another approach but I would like to be consistent with the code. I don't get any errors so I don't know what to do although I have been working around and looking for the answer on Internet.


Answer:
There's an important one character difference:
utf8
utf-8
Question: Cannot Mock but can Mock?

I am trying to build a mock factory, like this:
public Mock<T> CreateMock<T>(SomeParams someParams) where T : IMyInterface
{
    Mock<T> result = new Mock<T>();
    ...
}

However, I am getting the compiler error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Mock'.
Yet, when I tried this, it worked just fine:
public Mock<IMyInterface> CreateMock(SomeParams someParams)
{
    Mock<IMyInterface> result = new Mock<IMyInterface>();
    ...
}

I don't understand, why I am getting the compiler error, when the code is functionally the same? Is there any simple way to workaround this? I would like to avoid the second approach, as it would require considerable changes in our testing infrastructure.


Answer:

I don't understand, why I am getting the compiler error, when the code is functionally the same?

Consider this case:
public struct Awkward : IMyInterface
{
}
...
Mock<Awkward> mock = MockFactory.CreateMock<Awkward>();

That satisfies the constraint you've put on CreateMock - but Awkward is a value type. Mock<T> requires T to be a reference type.
You need to constrain the T type parameter in your method to be a reference type that implements the interface:
public Mock<T> CreateMock<T>(SomeParams someParams) where T : class, IMyInterface
Question: Does an error existe on the next code? it shows error on line 7

import pandas as pd
from sklearn.cluster import KMeans

dataset = pd.read_csv("smogon.csv")
dataset.drop(["url", 'texto'], axis=1, inplace=True)
km = KMeans(n_clusters=1, n_init='auto')
cluster = km.fit_predict(dataset[["moves"]])
dataset["Grupo"] = cluster
print(dataset)

it shows (cluster = km.fit_predict(dataset[["moves"]])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
also it shows ( could not convert string to float)
im doing a project with kmeans and pandas and when im trying to do the clustering with the csv file it shows an error but when i do it with another csv file, it doesnt show any problem running it.


Answer:
Try to use LabelEncoder to convert your column moves as numeric:
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder

dataset = pd.read_csv("smogon.csv")
dataset.drop(["url", 'texto'], axis=1, inplace=True)

# It does not make sense to have only one cluster...
# There is many documentation to find the best number of clusters (elbow method, ...)
km = KMeans(n_clusters=3, n_init='auto')
lbe = LabelEncoder()
dataset['moves_num'] = lbe.fit_transform(dataset['moves'])

cluster = km.fit_predict(dataset[['moves_num']])
dataset["Grupo"] = cluster
print(dataset)
Question: Regex to detect deformed words

I need to detect if a string contains a specific word like "Hello".

Hello -> yes
HhhheeeEEEElllLLLLoooOOOO -> Yes
hell0 -> yes
h   e l    l o / h. e .l .L . o -> Yes
h@@$$eee///LLL!!!ooo -> yes

My attempt:
let string = "h@@$$eee///LLL!!!ooo";

if (string.match(/\bhello\b/i)) {
      console.log("Yes");
} else {
      console.log("No");
}



Answer:
You can use .* between the chars, [o0] for o and zero and the flag i for case-insensitive matches:


[
  "h@@$$eee///LLL!!!ooo",
  "Hello",
  "HhhheeeEEEElllLLLLoooOOOO",
  "hell0",
  "h   e l    l o / h. e .l .L . o",
  "h@@$$eee///LLL!!!ooo"
].forEach(string => {
  if (string.match(/h.*e.*l.*l.*[o0]/i)) {
    console.log("Yes");
  } else {
    console.log("No");
  }
});



You can use a dynamic regular expression:


const input = "Hello";
const re = new RegExp(input.toLowerCase().split('').map(c => c === 'o' ? '[o0]' : c).join('.*'), 'i');

[
  "h@@$$eee///LLL!!!ooo",
  "Hello",
  "HhhheeeEEEElllLLLLoooOOOO",
  "hell0",
  "h   e l    l o / h. e .l .L . o",
  "h@@$$eee///LLL!!!ooo"
].forEach(string => {
  if (string.match(re)) {
    console.log("Yes");
  } else {
    console.log("No");
  }
});



I used an additional toLowerCase to simplify the replacement of o => [o0].
Question: Retrieve every value between an alphanumeric range in R using ifelse

This is my df:
df <- data.frame(id=as.integer(c(1:6)),
                 code=as.character(c("C410", "D486", "D485", "D501", "D600", "D899")))
df
  id code
1  1 C410
2  2 D486
3  3 D485
4  4 D501
5  5 D600
6  6 D899

I want to attribute causes to each id depending on the range they fall into in column 2. For this, I use a ifelse statement:
    df$cause <- ifelse(df$code >= "C00" & df$code <= "D48", "cause 1", 
                       ifelse(df$code >= "D50" & df$code <= "D89", "cause 2", NA)) 

Issue: the algorithm does not capture values above the end of each range (until the maximum possible value)
df
  id code   cause
1  1 C410 cause 1
2  2 D486    <NA>
3  3 D485    <NA>
4  4 D501 cause 2
5  5 D600 cause 2
6  6 D899    <NA>

Desired output:
 df
      id code   cause
    1  1 C410 cause 1
    2  2 D486 cause 1
    3  3 D485 cause 1  
    4  4 D501 cause 2
    5  5 D600 cause 2
    6  6 D899 cause 2



Answer:
Yo need to add a third digit:
df$cause <- ifelse(df$code >= "C000" & df$code <= "D489", "cause 1", 
                   ifelse(df$code >= "D500" & df$code <= "D899", "cause 2", NA))


> df
  id code   cause
1  1 C410 cause 1
2  2 D486 cause 1
3  3 D485 cause 1
4  4 D501 cause 2
5  5 D600 cause 2
6  6 D899 cause 2
Question: When using join in a string, I get too many characters in the string

I am trying to join an underscore into a string, but when running the code I get 4 times the character i used
str = potetoBox

for indx in range (len(str)):
    if str[indx].isupper():
        #split before indx and input an underscore
        str = ''.join((str[:indx],'_',str[indx:]))

print(str)

I have tried to change characters and change the order of the code. I expected to get only one underscore.


Answer:
Another solution without re that doesn't build a list:
result = ""
for c in my_str:
    result += "_" * c.isupper() + c
Question: How to copy from byte[] to new byte[] with some changed element item?

I have byte[] like this, the length of byte[] is 16, and I want to change some value of an item and add this to a new byte[]. For example, the value of byte[7] is 13, I want to change this value with a new value. After that, add into a new byte, the value of byte[7] will be changed plus one more unit.




Answer:
You should perform the operations the other way round. First copy then change the value in the copied data. This way the original will stay unchanged.
Efficient:
var original = new byte[]{1,2,3};
var result = new byte[original.Length];

Array.Copy(original, result, original.Length); //first make a copy
result[2] = 42; //then set your new value
//result is now [1, 2, 42]

Simple with LINQ:
//do not forget using System.Linq;
var original = new byte[]{1,2,3};

var result = original.ToArray(); //first copy
result[2] = 42; //then set your new value
//result is now [1, 2, 42]

For small data there will be no difference in performance. For large arrays the direct copy should perform a bit better. See this answer for further alternatives regarding the copy part.
Question: I am trying to remove an item from my mongoDb object which is an object with an array of nested objects. But this code is not working

I want to delete the object where the name is "Sleep".
The code I am using:
const listName = "Holiday;
  const item = new Item({
    name: "Sleep"
  });
  User.updateOne({username : req.user.username}, {$pull:{"lists.$[updateList].items" : item}}, {
    "arrayFilters": [
      {"updateList.name" : listName}
    ]
  }).exec().then(function(){
    console.log("Deleted successfully");
    res.redirect("/list-"+listName);
  })

The mongodb object:
  "_id" : ObjectId("64797ebc9e84ed9d8be3ea54"),
  "username" : "aryan@gmail.com",
  "lists" : [
      {
          "name" : "Holiday",
          "items" : [
              {
                  "name" : "Welcome to your todo-list!",
                  "_id" : ObjectId("647988267f3ddfc2982f7d77")
              },
              {
                  "name" : "Click + to add another item.",
                  "_id" : ObjectId("647988267f3ddfc2982f7d78")
              },
              {
                  "name" : "<-- Click this to delete an item.",
                  "_id" : ObjectId("647988267f3ddfc2982f7d79")
              },
              {
                  "name" : "Sleep",
                  "_id" : ObjectId("64799279c3da415dc4ce7574")
              },
              {
                  "name" : "WakeUp",
                  "_id" : ObjectId("6479930e6d49e494aad1dffa")
              }
          ],
          "_id" : ObjectId("647988357f3ddfc2982f7d85")
      }
]
}

It seems there is some problem with the updateOne and $pull: attributes but I can't figure out what.


Answer:
Try with
const listName = 'Holiday';
User.updateOne(
  { username: req.user.username, 'lists.name': listName },
  { $pull: { 'lists.$[].items': { name: 'Sleep ' } } }
)
  .exec()
  .then(function () {
    console.log('Deleted successfully');
    res.redirect('/list-' + listName);
  });
Question: questions is undefined in useEffect

I'm trying to display all the questions from this data set however it's only working sometimes and then other times I receive 'questions is undefined'.
Why am I receiving this error?
const [questions, setQuestions] = useState<any>();
const [question, setQuestion] = useState<string>()
const [answers, setAnswers] = useState<[]>()

useEffect(() => {
    fetch("/environment_questions")
      .then((response) => response.json())
      .then((data) => setQuestions(data));
    }, []);
  
    useEffect(() => {
      if (questions.length > 0) {
        for (let i = 0, l = questions.length; i < l; i++) {
          setQuestion(questions[i].question)
          setAnswers(questions[i].answers)
        }
      }
    }, [questions])
return (
<p>{JSON.stringify(question)}</p>
      <p>{JSON.stringify(answers)}</p>
)
}

Data I'm trying to access:
[{"id":1,"question":"...":[{"id":1,"answer":"..."},{"id":2,"answer":"..."}]},{"id":2,"question":"...","answers":[{"id":1,"answer":""},{"id":2,"answer":""},{"id":3,"answer":""}]} ...}]


Answer:
import React, { useEffect, useState } from 'react'

const Component = () => {
  const [questions, setQuestions] = useState<any>()
  const [question, setQuestion] = useState<string>()
  const [answers, setAnswers] = useState<[]>()

  useEffect(() => {
    fetch('/...')
      .then(response => response.json())
      .then(data => setQuestions(data))
  }, [])

  useEffect(() => {
    if (questions.length > 0) {
      for (let i = 0, l = questions.length; i < l; i++) {
        setQuestion(questions[i].question)
        setAnswers(questions[i].answers)
      }
    }
  }, [questions])

  return (
    <>
      <p>{JSON.stringify(question)}</p>
      <p>{JSON.stringify(answers)}</p>
    </>
  )
}

export default Component
Question: Add a Column with a string value based on other column values R

I want to add one a column called "Opt-Numbers" to my data frame with the following values Opt-CMM and Opt-MM based on Numbers column. If the value in Numbers column are greater or equal to 4 then it should add Opt-CMM in the same row of that value or if it is less than 4 then add Opt-MM in the same row. I am also showing an example in below df.
Given DF.




S.NO
Numbers




P1
2


P2
5


P3
2


P4
2


P5
3


P6
4




Required DF




S.NO
Numbers
Opt-Numbers




P1
2
Opt-MM


P2
5
Opt-CMM


P3
2
Opt-MM


P4
2
Opt-MM


P5
3
Opt-MM


P6
4
Opt-CMM





Answer:
We can do this with dplyr and case_when ()
library(dplyr)

#example data
data <- structure(list(S.NO = c("P1", "P2", "P3", "P4", "P5", "P6"), Numbers = c(2, 5, 2, 2, 3, 4)), class = "data.frame", row.names = c(NA, -6L))

create new column with filters
data <- data %>%
          mutate(Opt-Numbers = case_when(
                    Numbers >= 4 ~ "Opt-CMM",
                    Numbers < 4 ~ "Opt-MM"
          ))

data
Question: How can I use clip-path to achieve a text effect on my SVG in the browser?

I want to use clip-path to implement effect like: svg with text clip-path,  but open in browser it just display an empty
svg.  I wrap the path with <g> tag, then it failed.
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none" style="
    width: 200px;
    height:  200px;
">
    <defs>
        <clipPath id="text-path">
            <g clip-rule="evenodd" fill-rule="evenodd">
                <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
                <path d="M16 0L24 8H16V0Z"/>
                <text x="7.5" y="23">PDF</text>
            </g>
        </clipPath>
    </defs>
    <g clip-path="url(#text-path)" fill="red">
        <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
        <path d="M16 0L24 8H16V0Z"/>
    </g>

    <style>
        text {dominant-baseline: hanging;font-size: 8px;font-weight: bold;}
    </style>
</svg>

it should be displayed in browser.


Answer:
In your example (above) you may remove the wrapping group around the 2 paths and the text and it would work.
 <clipPath id="text-path">
        <!-- <g clip-rule="evenodd" fill-rule="evenodd"> -->
            <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z"/>
            <path d="M16 0L24 8H16V0Z"/>
            <text x="7.5" y="23">PDF</text>
        <!-- </g> -->
 </clipPath>

However you won't see the text.
If what you need is to see the text as a hole in the shapes you will need a mask where the text is black and the 2 paths are white. In the case of the mask  you can use a group if you think you need it.


<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" style="
    width: 200px;
    height:  200px;
    background:silver">
  <mask id="m">
  <g fill="white">
    <path d="M0 0H14V2H2V13H22V10H24V13H32V27H24V32H0V0ZM2 30V27H22V30H2Z" />
    <path d="M16 0L24 8H16V0Z" />
  </g>
    <text x="7.5" y="23" fill="black">PDF</text>
  </mask>

  <rect width="32" height="32" mask="url(#m)" fill="red" />

  <style>
    text {
      dominant-baseline: hanging;
      font-size: 8px;
      font-weight: bold;
    }
  </style>

</svg>
Question: Vuejs. is it possible to pass a function returned from another function to event handler?

<template>
  <v-list-item v-for="(category, i) in categories" :key="i">
    <v-item-group multiple @update:model-value="selectedChanged(category)">
       <v-item></v-item>
    </v-item-group>
  </v-list-item>
</template>

<script>
  function selectedChanged(category) {
    return function(items) {
      console.log(`select ${items} from ${category}`);
    }
  }
</script>

I hope that, in function selectedChanged, I can know which category was selected. But it doesn't work. Vue just called selectedChanged with parameter category.
The reason why I want to do this is that, if I define selectedChanged as follows:
function selectedChanged(items) {
  console.log(items);
}

I don't know which category was selected.
How to impelement function selectedChanged so that I can know which category was selected?


Answer:
Like Estus said in the comments, it looks like what you want can probably be achieved by explicitly passing $event as one of your event handler arguments. (Here is a link to the relevant Vue 3 documentation on $event.) The code would look something like this:
<template>
  <v-list-item v-for="(category, i) in categories" :key="i">
    <v-item-group multiple @update:model-value="selectedChanged(category, $event)">
       <v-item></v-item>
    </v-item-group>
  </v-list-item>
</template>

<script>
  function selectedChanged(category, items) {
    console.log(`select ${items} from ${category}`);
  }
</script>

Of course, this solution assumes that the items you're looking for are emitted by the update:model-value call in (what I assume to be) Vuetify. You might need to do some destructuring or refactoring to get precisely what you want.
Question: OR-TOOLS Job Shop Scheduling - stop when find first feasible solution

I am trying to implement Job Shop Scheduling with CP-SAT, but I have more than 20000 tasks to schedule and finding optimal solution will take too much time. I'm using solver time limit, but sometimes it gives me feasible solution in assumed time and sometimes not. Could anyone show how to limit solver to find the first feasible solution?
https://developers.google.com/optimization/scheduling/job_shop
I know that I should use SolveWithSolutionCallback, but I don't know how.


Answer:
set the parameter: stop_after_first_solution to true.
See the definition.
Question: Is it possible to exclude certain fields using JSONATA?

Using JSONATA, is it possible to exclude certain fields that are nested in a deep structure without using object construction? For example, with the following object
{
    "collection": [
        {
            "id": "ABC",            
            "learningunit": {
                "metadata": {
                    "show": true,
                    "unitType": {
                        "code": "U",                        
                        "value": "Unit"
                    }                   
                }
            }
        },
        {
            "id": "UYE",            
            "learningunit": {
                "metadata": {
                    "show": false,
                    "unitType": {
                        "code": "C",                        
                        "value": "COURSE"
                    }                   
                }
            }
        }
    ]
}

can we exclude the field "show" and "value" in order to get the following result.
{
    "collection": [
        {
            "id": "ABC",            
            "learningunit": {
                "metadata": {                   
                    "unitType": {
                        "code": "U"                     
                    }                   
                }
            }
        },
        {
            "id": "UYE",            
            "learningunit": {
                "metadata": {                   
                    "unitType": {
                        "code": "C"                     
                    }                   
                }
            }
        }
    ]
}

FYI, the following object construction expression does the job but it is cumbersome to write if the object is complex.
{"collection":collection.
    {
    "id": id,
    "learningunit": learningunit.
        { 
            "metadata": metadata. 
            {
                "unitType": unitType.
                {
                    "code": code
                }
            }
        }
    }
} 



Answer:
You can make use of the transform operator and remove all 'value' and 'show' fields from the nested structure:
$$ ~> | ** | {}, ['show', 'value'] |

See it on the live Stedi playground: https://stedi.link/Usc1tpg
Note that if you need to clear those on a specific path only, you can also do it more surgically:
$$
  ~> | *.learningunit.metadata | {}, ['show'] |
  ~> | *.learningunit.metadata.unitType | {}, ['value'] |

Playground: https://stedi.link/Bh8cUiM
Question: How to count number of consecutive Trues in a numpy array along a given axis?

I have for example the following np array
array([[ True, False, False],
       [False,  True,  True],
       [ True,  True,  True],
       [False,  True,  True],
       [False,  True,  True],
       [ True, False, False],
       [ True,  True, False],
       [False, False,  True]])

I want to count the number of consecutive Trues along the columns, so in the above example, the first column contains 3 blocks of consecutive Trues, the second column contains 2 blocks, and the third contains 2 blocks. The output should then be
array([3, 2, 2])

I know I can do loops for each columns, like in this answer for a one-dimensional array, but what is a numpy-way for doing this on a 2-d array?


Answer:
Use boolean arithmetic to identify the True that are not followed by a True (using slicing and pad), then sum the True per column:
out = ((a != np.pad(a[1:], ((0,1), (0,0)), constant_values=False))
       & a).sum(axis=0)

Or:
out = (a & ~np.pad(a[1:], ((0,1), (0,0)), constant_values=False)).sum(axis=0)

Output:
array([3, 2, 2])
Question: resolve write problem when write to Cassandra replica set

By design we can write to any node in the Cassandra replica set. For situation my replica set has 2 node. When I make a write operation to node A but the node is unavailable. Do I have catch exception then re-write to node B manually ?
On mongodb, their Driver have "Retry-able Writes" to auto write to another node if primary node is down. Does Cassandra have this feature ?


Answer:
When you write to Cassandra you specify the consistency level you wish to write wish - ranging from ANY which provides no guarantees, up to ALL which requests that all replicas in all DCs acknowledge back to the co-ordinator.
This write is sent to a single node - based on your load balancing policy - that node acts as the co-ordinator for the whole operation, and will return a single response of success / exception- your application does not have to itself individually send the write to multiple nodes, it just sends to 1 node (any node can be used) who co-ordinates the write to the replicas.
In a normal scenario of using local_quorum for a write with a very normal replication factor of 3 then as long as the co-ordinator has 2 of the 3 nodes providing acknowledgement of the write, the application will not get any exception - even if the 3rd node fails to write the data.
There is a retry policy available on the driver - which can allow for a retry in the event of a timeout, you should ensure though that the operation is idempotent when using this. (for example, appending an item to a list, retrying could result in the item being on the list twice on one of the replicas).
With your particular replication factor being 2 - you are currently in a position where you are lack consistency guarantees, or resilience.

one / local_one - only guarantees one of the nodes got the write. (Both are likely to get it but there is no guarantee provided)
quorum / local_quorum - requires both nodes acknowledge, so you have no ability to handle a node failure.

This is because the quorum of 2 is 2 - if you used 3 nodes with an RF=3, then local_quorum requires 2 of the 3, which would allow a node to be down while providing a stronger guarantee on consistency.