satoshi-2000/llms-suitable huggingface dataset:
Question: Defining an emacs minor mode

Have coded an emacs minor mode with the definition shown below.
Would it be possible to simplify this, to perhaps call a function instead?  Or is it not such a big deal having a minor-mode defined in this way ?
What would be the general way to set a minor-mode in terms of functionality (e.g. enable, disable, ...) ?
(defcustom komis-luna-signal t
  "todo"
  :group 'komis-luna)

;;;###autoload
(define-minor-mode komis-luna-minor-mode
  "Uses large geometric shapes for displaying heading levels."
  nil nil nil

  (let*
      (($keyword
        `(("^\\*+ "
           (0 (let* ( ($kondor
                         (- (match-end 0) (match-beginning 0) 1))
                      ($inline-task
                         (and (boundp 'org-inlinetask-min-level)
                              (>= $kondor org-inlinetask-min-level))) )
                ;;--------------------------------------
                (compose-region (- (match-end 0) 2)
                                (- (match-end 0) 1)
                                (komis-luna-shape-select $kondor))
               ;;---------------------------------------
               (when $inline-task
                  (compose-region (- (match-end 0) 3)
                                  (- (match-end 0) 2)
                                  (komis-luna-shape-select $kondor)))
               ;;---------------------------------------
               (when (facep komis-luna-typeface)
                  (put-text-property
                     (- (match-end 0) (if $inline-task 3 2))
                     (- (match-end 0) 1)
                     'face komis-luna-typeface))
               ;;---------------------------------------
               (put-text-property
                  (match-beginning 0)
                  (- (match-end 0) 2)
                  'face (list :foreground
                        (face-attribute 'default :background)))
               ;;---------------------------------------
               (put-text-property (match-beginning 0)
                                  (match-end 0)
                                  'keymap komis-luna-mouse-sweep)
               ;;---------------------------------------
               nil )) ))))

    (if komis-luna-signal

        (progn
          (font-lock-add-keywords nil $keyword)
          (font-lock-fontify-buffer))

      (save-excursion
        (goto-char (point-min))
        (font-lock-remove-keywords nil $keyword)
        (while (re-search-forward "^\\*+ " nil t)
          (decompose-region (match-beginning 0) (match-end 0)) )
        (font-lock-fontify-buffer)) ) ))



Answer:
I think you did it the proper way.
Next would be to toggle your minor mode in your emacs configuration file .emacs.d/init.el with a hook probably like this :
(add-hook 'org-mode-hook 'komis-luna-minor-mode)

If you want your minor mode to be enable when entering org-mode.
For further and more specifics questions and problems, you should probably take this post to Emacs Stack Exchange.
Question: Cannot write a paragraph to a pdf file using iText pdf

I am using Java 17 and the iText pdf library (5.5.4), I'm currently attempting to write a paragraph on an existing pdf file inside a rectangular area, however I seem to have a NullPointerExeption when invoking the go() method, I'm not sure exactly why. I have included my code, any help would be appreciated.
public class Main {
    public static void main(String[] args) {
        try {

            PdfReader reader = new PdfReader("src/main/resources/test_file.pdf");


            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("src/main/resources/output.pdf"));

            PdfContentByte cb = stamper.getOverContent(1);
            ColumnText ct = new ColumnText(cb);
            ct.setSimpleColumn(new Rectangle(36, 600, 200, 800));
            ct.addElement(new Paragraph("I want to add this text in a rectangle defined by the coordinates llx = 36, lly = 600, urx = 200, ury = 800"));
            int status = ct.go();



        } catch (DocumentException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.itextpdf.text.pdf.PdfStructureElement.getAttribute(com.itextpdf.text.pdf.PdfName)" because "this.parent" is null


Answer:
I could reproduce your issue using your example file with iText 5.5.4. Then I tried again with the current 5.5.13.3. There was no issue. Thus, please update.
Comparing the 5.5.4 code (where the exception occurs) with the corrsponding 5.5.13.3 code, one sees that there indeed was an unconditional call of a method of a parent object but that now there is a call to a helper method that first checks the parent and only calls its method if it isn't null.
This fix has been applied in early 2015, the commit comment was "Fixed NPE when modifying content of TaggedPDF document.".
Question: Kafka consumer unique cluster ID?

Does a Kafka cluster have some unique ID that I can get programmatically out of a Kafka consumer? I checked for message headers, but it looks like there's no metadata in them by default and I don't see any methods in a KafkaConsumer or ConsumerRecord for retrieving such a value either.


Answer:
You can use AdminClient to get the cluster id, but generally, there's no reason for clients to know internal server information
Question: How to return 0 for all time intervals instead of nothing when counting

I have a query for deployment table. There is no data for hotfix column now. I want to show all change count without hotfix and with hotfix for time intervals.
Table data:




deployTime
changeno
hotfix




2022-08
aaa



2022-08
bbb



2022-11
ccc



2023-01
ddd





First attempted query:
SELECT deployTime               AS times ,   
       COUNT(DISTINCT changeno) AS "Change Count" 
FROM deployments 
WHERE hotfix = ''
GROUP BY deployTime 

which returns all dates with Change count:




times
ChangeCount




2022-08
2


2022-11
1


2023-01
1




Second attempted query:
SELECT deployTime               AS times ,   
       COUNT(DISTINCT changeno) AS "Change Count" 
FROM deployments 
WHERE hotfix != ''
GROUP BY deployTime 

which returns no records if there's no record with hotfix != ''.
How we can get 0 count for every date instead of nothing?




times
HotfixCount




2022-08
0


2022-11
0


2023-01
0




Thanks


Answer:
The problem with your query is that you're using a WHERE clause, that removes records. What you should do instead, is apply conditional aggregation on presence/absence of hotfix values:
SELECT deployTime AS times ,   
       COUNT(DISTINCT changeno) FILTER(WHERE hotfix = '') AS "Change Count" 
FROM deployments 
GROUP BY deployTime 

And change it to WHERE NOT hotfix = '' conversely to obtain zeroes.
Check the demo here.
Note: It's better to have NULL values instead of empty strings, when you need to indicate missing data.
Question: How do I break down data that I am grouping by?

I have a table where each instance in the table is a sold ticket and tickets can have different ticket types. Looking something like this:




Event
Ticket Type




Event 1
a


Event 2
a


Event 1
b


Event 2
a


Event 1
a




I want it to be grouped by the event but displaying both the total tickets for that event as well as breaking down the number of each ticket type.




Event
Total Tickets
Ticket Type a
Ticket Type b




Event 1
3
2
1


Event 2
2
2
0




I have tried a few different queries but nothing that is showing me the results I'm looking for. Is this possible in one query?


Answer:
Yes, it is possible by using GROUP BY to group the event data and then calculating the totals. The following query works by counting the number of tickets, then counting the number of tickets for each type "a" and "b".
SELECT 
    Event,
    COUNT(*) AS 'Total Tickets',
    COUNT(CASE WHEN TicketType = 'a' THEN 1 END) AS 'Ticket Type a',
    COUNT(CASE WHEN TicketType = 'b' THEN 1 END) AS 'Ticket Type b'
FROM
    Tickets
GROUP BY
    Event;
Question: Polymorphic serialization of property

I'm trying to create a Client library that will allow users to push serialized data to a service.
so I created a class
public class Data
{
   public string Prop1 {get; set;}
   public SubData Prop2 {get; set;}
}

public abstract class SubData
{
   public string Prop3 {get; set;}
}

I would like to allow users to extend that SubData to add custom properties. but I'm having issues in my Serialization, it doesn't serialize the properties of the extended inner object
JsonSerializer.Serialize(data) 

I know that I could decorate my SubData class with JsonDerivedType attribute, but my problem is that SubData is in a package, and it doesn't know about who will extend it and with what (and it doesn't care)
I don't know if I'm clear what my problem is so here is a full test to replicate:
using System.Text.Json;

public class Data
{
    public string Prop1 { get; set; }
    public SubData SubData { get; set; }
}

public abstract class SubData
{
    public string Prop2 { get; set; }
}

public class ExtendedSubData : SubData
{
    public string Prop3 { get; set; }

}

var data = new Data
{
    Prop1 = "1",
    SubData = new ExtendedSubData
    {
        Prop2 = "2",
        Prop3 = "3"
    }
};

SerializData(data);

void SerializData(Data data)
{
    var serialized = JsonSerializer.Serialize<object>(data);
    // serialized at this point doesn't contain Prop3 of 
    // ExtendedSubData
}



Answer:
As an alternative to the custom JsonConverter, you can replace the SubData property with generic
public class Data<TSubData>
    where TSubData : SubData
{
    public string Prop1 { get; set; }
    public TSubData SubData { get; set; }
}

string SerializData<TSubData>(Data<TSubData> data)
    where TSubData : SubData
{
    return JsonSerializer.Serialize<object>(data);
}

Test it on dotnetfiddle:
https://dotnetfiddle.net/lkOM0Z
Question: How to sign dylib file which can be replaced?

I have poor understanding in this question. The major step to distribute any application is the code signing, it signs application with dependant dynamic library. As I understand OS will check signed application during installation and subsequent calls. If application or dynamic library was changed then os rejects the launch. Many dylib files are supplied to conform LGPL license and therefore dylib files can be potentially substituted by user later. But it will break the launch of application (because signed dylib was replaced). Are my assumptions correct? Maybe there is comprehensive book/guide which covers this topic? I found apple documentation pretty bad


Answer:
That's not how this works.
The signature of the library isn't going to matter if the entire library will be replaced. What matters is the signature of the main executable of the process, specifically whether it enforces library validation. But even if you disable library validation, that is likely only going to work for dlopen() scenarios.
The problem is that app bundles are signed as a whole. Even non-executable resource files within the bundle are hashed, and then this list of hashes is hashed again and stored in the code signature of the main binary. While it looks syntactically possible to exclude files from this, I don't know whether Gatekeeper would accept this, and I don't know whether it would work for dylibs in particular.
But even if you found a combination that works, it will likely only be a matter of time before Apple breaks it, because the whole point of codesigning is that only pre-approved binaries are allowed to be executed.
The simple solution is: if you replace the library, you re-sign the entire bundle.
Question: Cannot run updated file from terminal of VSC, for Python

So to make it very simple.
If I write print("Hello World") and run it on the RUN icon on top right corner it works perfectly fine.
And only then if I type in terminal   python hello.py   executes again just fine.
But if I change program to print("Hello to everybody") and I type in terminal   python hello.py   it executes the previous program and giving me Hello World on screen. But then again if I click on run icon and after correct execution repeat in terminal python hello.py, now it runs correctly.
Well I tried CTRL,SHift P, to change terminal and like select interpreter but couldn't figure out from which file is it trying to start program. And why is it correct after I use run icon.


Answer:
Are you saving the file after changing it? The Run button will run the code that is currently in the editor, while running it via python in the command line will run it from the saved file.
Question: Vue 3: Mount component onto existing app instance

I have a plugin written in Vue 2 that programmatically mounts a component onto existing app instance.
export default {
  install (Vue) {
    const component = new (Vue.extend(Component))()
    const vm = component.$mount()
    document.body.appendChild(vm.$el)
  }
}

Trying to migrate this to Vue 3 and this is the closest I've got.
export default {
  install (app) {
    const component = defineComponent(Component)
    const container = document.createElement('div')
    document.body.appendChild(container)
    const vm = createApp(component).mount(container)
  }
}

The problem is that createApp creates a new app instance, while Vue.extend created only a subclass. I need to have all globally available components in the main app, available in plugin's component as well. Creating a new app instance prevents this.
Component needs to be programatically mounted. Manually inserting it into template is not an option.
Please help.


Answer:
Interesting problem! There is a discussion on the Vue GitHub and they created a module that you can use: mount-vue-component. I found it very helpful to look at the module's code, it does exactly what you want to do.
To instantiate the component, you have to create a VNode, which you can do with createVNode() (which is the same as h()). To get access to the app's context, including global components, you have to set the appContext property. Finally, the render() function mounts the component instance to an HTML Element.
So for you example, that gives you:
export default {
  install (app) {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const vNode = createVNode(component)
    vNode.appContext = app._context
    render(vNode, container)
  }
}


Here it is in a snippet:


const { createApp, createVNode, ref, render  } = Vue;

const App = {
  data() {
    return {
      msg: ref('Hello from app!')
    }  
  }
}
const app = createApp(App)

app.component('inner-component', {
  template:  '<div style="color: green;">This is a global component in app</div>'
})
app.mount('#app')


const component = {
  props: ['color'],
  template: '<span :style="{color: color}">Hello from mounted component!</span><inner-component></inner-component>'
}
const el = document.getElementById('leComponent')
const vNode = createVNode(component, {color: 'blue'}, [])
vNode.appContext = app._context
render(vNode, el)
div{
  margin: 4px;
  padding: 4px;
  border: 1px solid #333;
}
<div id="app">
  {{msg}}
  <inner-component></inner-component>
</div>
<div id="leComponent"></div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
Question: Matrix Circuit Analysis using Algorithms

spsolve is then - sometimes - unable to find a solution.
Our teacher gave us test cases that we have to satisfy however I passed all of them but seems to fail the hidden test cases.
My code checks for the following: If they share a node and only those two resistors are connected then print SERIES else NEITHER. If their previous resistor is in series, then its is in SERIES (see test case no 2). If the resistor's ends are connected to the same nodes then print Parallel.
Can you suggest some inputs or any possible scenarios that a code wouldn't be able to answer correctly? or maybe a suggestion on what type of algorithm I should use for this problem
As I am performing nodal analysis, a singular matrix is expected since the position of the ground potential is generally not well-defined. However, before the update, a solution was found in 99% of the cases, maybe more. Now, I'm at 10% for large systems at best. I have not changed the algorithm and for a few tests, I have used identical code as before. Here is how I set up my calculation:
I generate a random three-dimensional network of resistors (I realize that I could accidentally create unsolvable networks but the percentages above should not change that drastically). The only SciPy/NumPy functions used here is np.random
I create a sparse lil-matrix which I fill with conductance values extracted from my resistor network. I also create a solution vector which is not sparse.
I convert the conductance matrix to csr-format and use the spsolve method. This is where my code lately fails.


Answer:
Electron travel between Vdd and ground.  The Dijkstra algorithm ( google it ) finds these routes.  If two resisters are on the same route, they are in series.
Setup

LOOP over every pair of resisters

IF the ends of the two resistor are connected to the same nodes
- mark as parallel


Create adjacency list for resisters, combining parallels together into one edge.

To check if R1 and R2 are in series:

IF R1 and R2 are marked parallel return PARALLEL
Use Dijkstra to find all routes from Vdd to R1
IF no route return NO
Use Dijkstra to find all route from R1 to GND
IF no route return NO
IF R2 itself, or as part of a parallel, on any routes found return SERIES

Note that this will return YES for R3 and R4 in sample input 1.  I do not understand why R3 and R4 are not in series - electricity will flow through R3 and then R4 to reach ground.
Obviously, I do not understand your definition of "in series".  Please provide this definition.  In particular:
R1 Vdd a
R2 a b
R3 a b
R4 b GND

Are R1 and R4 in series or not?
Question: Does a StatefulSet pod, when deleted or failed, get redeployed on the same worker node, or is it deployed on another available worker node?

Does a StatefulSet pod, when deleted or failed, get redeployed on the same worker node, or is it deployed on another available worker node?
Seeking clarification on the default behavior of StatefulSet pods in Kubernetes when they are deleted or failed whether they are rescheduled on the same worker node or on different worker nodes.


Answer:
By default, k8s will schedule a new pod on any 1 of the nodes which has sufficient CPU and memory resources available. If you specified any special conditions like Pod affinity, Pod affinity or Node affinity, k8s will follow them accordingly. Please check out this official document
Question: Image duplicated when using fig.canvas.tostring_rgb()

I am plotting 3D data using matplotlib==3.3.4:
fig = plt.figure(figsize=(15, 10))
ax = fig.gca(projection="3d")
ax.view_init(30, 0)

# facecolors is a 3D volume with some processing
ax.voxels(
    x, y, z, facecolors[:, :, :, -1] != 0, facecolors=facecolors, shade=False
)
fig.canvas.draw()
image_flat = np.frombuffer(fig.canvas.tostring_rgb(), dtype="uint8")
image_shape = (*fig.canvas.get_width_height(), 3)  # (1500, 1000, 3)
ax.imshow(image_flat.reshape(*image_shape))
plt.show()

(I am making some improvements on BraTS20_3dUnet_3dAutoEncoder with inspiration from Figure to image as a numpy array).
However, when I actually plot the image, there are two copies:

What am I doing wrong?  I can't figure out where the second image is coming from.


Answer:
The NumPy array ordering is (rows, cols, ch). The code image_shape = (*fig.canvas.get_width_height(), 3) switches rows and cols, which leads to the output image being incorrectly shaped, which looks like two copies.

Replace image_shape = (*fig.canvas.get_width_height(), 3) with:
image_shape = (*fig.canvas.get_width_height()[::-1], 3)


For avoiding confusion, we better use two lines of code:
cols, rows = fig.canvas.get_width_height()
image_shape = (rows, cols, 3)


Reproducible example (using data from here):
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(15, 10))
ax = fig.gca(projection="3d")
ax.view_init(30, 0)

# https://stackoverflow.com/questions/76387953/image-duplicated-when-using-matplotlib-fig-canvas-tostring-rgb
# prepare some coordinates
x, y, z = np.indices((8, 8, 8))

# draw cuboids in the top left and bottom right corners, and a link between
# them
cube1 = (x < 3) & (y < 3) & (z < 3)
cube2 = (x >= 5) & (y >= 5) & (z >= 5)
link = abs(x - y) + abs(y - z) + abs(z - x) <= 2

# combine the objects into a single boolean array
voxelarray = cube1 | cube2 | link

# set the colors of each object
colors = np.empty(voxelarray.shape, dtype=object)
colors[link] = 'red'
colors[cube1] = 'blue'
colors[cube2] = 'green'

# and plot everything
#ax = plt.figure().add_subplot(projection='3d')
ax.voxels(voxelarray, facecolors=colors, edgecolor='k')

fig.canvas.draw()
image_flat = np.frombuffer(fig.canvas.tostring_rgb(), dtype="uint8")
#image_shape = (*fig.canvas.get_width_height(), 3)  # (1500, 1000, 3)
#image_shape = (*fig.canvas.get_width_height()[::-1], 3)  # It should be (1000, 1500, 3) instead of (1500, 1000, 3)
cols, rows = fig.canvas.get_width_height()
image_shape = (rows, cols, 3)
img = image_flat.reshape(*image_shape)

plt.figure()
plt.imshow(img)
plt.show()


Output image before fixing the code:

Output image after fixing the code:
Question: Are there any default value tricks / Elvis Operator in Ocaml?

Are there any elvis like operator in Ocaml ?
Any sort of optional chaining that return the right value when the left one is empty, a default value operator, like the |> operator with opposite effect.
If not what are the good practices ?
As an example of a use case :
let get_val val_1 val_2 = 
  if (val_1) then (val_1) else (val_2);;

Are there any syntactic sugar ?


Answer:
First, in OCaml if ... then ... else ...  is an expression and thus there is no needs to have a distinct ternary operator.
Second, OCaml has optional arguments.
If I guess correctly the supposed semantics of your get_val function, it can be written:
let default = []
let get_val ?(val_1=default) () = val_1

which gives you [] as the default value when the named argument val_1 is absent
let () =
  assert ([] = get_val ())

or the val_1 argument otherwise:
let () = 
  assert ([2;3;4] = get_val ~val_1:[2;3;4] ())
Question: send a get http request by axios on react to laravel 10 backend on localhost

i am using axios on react to send http request to laravel backend. but cors prevent laravel to answer my request. i catch below error:
p://localhost/todo/laravel/public/api/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my react code:
    axios.get('http://localhost/todo/laravel/public/api/test', { withCredentials: true })
        .then(function (response) {
            // handle success
            console.log(response);
        })
        .catch(function (error) {
            // handle error
            console.log(error);
        })
        .then(function () {
            // always executed
        });

my laravel code:
public function all(): bool|string
{
    $todos = Todo::all();
    return json_encode($todos);
}

my cors config:
<?php

return [

/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['*'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => false,

'supports_credentials' => false,
];

what is problem?


Answer:
try
'paths' => ['todo/*'],
I' not sure, that ['*'] is allowed