satoshi-2000/llms-suitable huggingface dataset:
Question: How to perform XML Element substitution in config.wxi using Replace Tokens?

I am building an Azure Devops Release pipeline and I have a WIX config file in my source code with the following structure
<?xml version="1.0" encoding="utf-8"?>
<Include>
  <?define Key ="MyValue"?>
</Include>

I would like to replace "MyValue" with "MyNewValue" using the Replace Tokens package
(link here)
Following the answer given here.
I have <Include> as my token prefix and </Include> as my token suffix. I've added the following pipeline variable:
enter image description here
When I build my pipeline it finds the file correctly, but doesn't find any variables to replace, am I missing something to link the variables step to the pipeline variables?
alternatively I was thinking the '<?' tags could be throwing it off or perhaps it's just not compatible with the WIX xml files?


Answer:
Why not just pass the preprocessor variable via the .wixproj or command-line (whichever way you are building). That way you avoid the include file completely and have a much simpler solution.
I cover this technique in Episode 12 of the Deployment Dojo - All the Ways to Change. Variables and Variables. Directories and Properties:
<Project Sdk="WixToolset.Sdk/4.0.0">
  <PropertyGroup>
   <DefineConstants>Key=MyValue</DefineConstants>
  </PropertyGroup>
</Project>

Then you can easily override the value with msbuild -p:Key=MyNewValue.
Question: ggplot - ordering legends with guides changes continuous legend to discrete

I'm running ggplot2 v3.4.1. I created this 2 legend plot that by default it is placing the year2 size legend below the cty color legend. However, I would like the size legend to be on top.
library(tidyverse)

mpg$year2 = factor(mpg$year)
values = c(2,4); names(values) = c("1999", "2008")
p = mpg %>%
  ggplot(aes(x = cty, y = hwy, color = cty, size = year2)) + 
  geom_point() +
  scale_size_manual(name = "year2", values = values)
p


Therefore, I used guides() to specify the legend ordering but it changes the continuous color legend cty to discrete
p + guides(size = guide_legend(order = 1), 
           color = guide_legend(order = 2))


I saw this post ggplot guide_legend argument changes continuous legend to discrete but am unable to figure out how to use guide_colorbar() when you have 2 or more legends.
How do I change my code to keep the cty legend as continuous? Thx


Answer:
It's simply
p + guides(size = guide_legend(order = 1), 
           color = guide_colorbar(order = 2))
Question: python3, converting integer to bytes: which are the alternatives to using to_bytes() for small integers?

Is there a more efficient method to convert an integer, in the range 0..255 (in C uint8), to one byte?
x = 100
x.to_bytes(1, "big")



Answer:
More efficient method for a single integer? Probably not.
Here's a comparison of the common ones:
python -m timeit -s "import struct" "struct.pack('<B', 100)"
2000000 loops, best of 5: 101 nsec per loop
python -m timeit "(100).to_bytes(1)"                     
5000000 loops, best of 5: 81.1 nsec per loop
python -m timeit "bytes([100])"     
2000000 loops, best of 5: 199 nsec per loop

If you're talking about multiple, bytes([integers]) will probably be the most efficient.
For some premature optimization you can cache the function, which will net you a few nanoseconds:
python -m timeit -s "tb = int.to_bytes" "tb(100,1)" 
5000000 loops, best of 5: 78.6 nsec per loop

And if you want the most efficient possible, it would probably be using a tuple:
python -m timeit -s "b=tuple(map(int.to_bytes, range(256)))" "b[100]"
10000000 loops, best of 5: 20.9 nsec per loop

But personally I find it disgusting.
Question: Simulate decaying function

Lets t be the time tick i.e. 1,2,3,4,5....
I want to calculate and plot a cumulative decaying function f(inits[],peaks[],peak-ticks,zero-ticks).
Preferably in python
Where :
- inits[] is a list of points at time/tick t where a new 'signal' is introduced
- peaks[] is a list of values which must be reached after peak-ticks. (corresponding to inits)
- peak-ticks is how many ticks it takes to reach the next peak value
- zero-ticks is how many ticks it takes to reach zero from the peak

For example :
 f(inits=[10,15,18], peaks=[1,1,1], peak-ticks=1, zero-ticks=10)

in this case decay takes 10 ticks i.e. 0.1 per tick.
at tick:
 10! result is 0
 11. = 1
 12. = 0.9
 .....
 15! = 0.6 + 0 = 0.6
 16. = 0.5 + 1 = 1.5
 17. = 0.4 + 0.9 = 1.3
 18! = 0.3 + 0.8 + 0 = 1.1
 19. = 0.2 + 0.7 + 1 = 1.9
 20. = 0.1 + 0.6 + 0.9 = 1.6
 .....

PS> As a complication, what if the decay is exponential like 1/x ?


Answer:
For the base case you mentioned, it is actually pretty simple, you just need to define a triangular function that returns the contribution of a specific singal at the current tick t.
Then, just sum the contribution of all signals at tick t, that is your answer.
In the code below, I implemented the decaying function as an infinite generator, so I have to use islice to define how many ticks to compute (or maybe the start and end ticks). You could also implement it as a normal function, you'd just have to pass in the start and end ticks.
from itertools import count, islice

def fdecay(inits, peaks, ptks, ztks):
  for t in count():
    yield sum(triang(p, i, i+ptks, i+ptks+ztks, t) for i, p in zip(inits, peaks))

def triang(ymax, xa, xb, xc, x):
  if x < xa: return 0
  if x < xb: return ymax * (x-xa) / (xb-xa)
  if x < xc: return ymax * (xc-x) / (xc-xb)
  return 0

x = list(islice(fdecay([10,15,18], [1,1,1], 1, 10), 30))
print(x)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0, 0.9, 0.8, 0.7, 0.6, 1.5, 1.3, 1.1, 1.9, 1.6, 1.3, 1.1, 0.9, 0.7, 0.5, 0.3, 0.2, 0.1, 0]


If you want exponential decay, just switch the triangular function to the exponential function at time t (with the appropriate params).
Question: Rails 7 - Accessing joined model generate new query

I have Rails 7 project where I've got tables
Pipelines
class Pipeline < ApplicationRecord
  has_many :states, inverse_of: :pipeline, dependent: :destroy  
end

States
class State < ApplicationRecord
  belongs_to :pipeline, inverse_of: :states 
  has_many :items, inverse_of: :state
end

Items
class Item < ApplicationRecord
  belongs_to :state, inverse_of: :items
end

I wrote a query to limit only specific items on state
@pipeline = Pipeline.joins(states: :items)
                    .where(states: { items: { name: "Lorem" } })
                    .find_by(id: '123')

query:
Pipeline Load (0.7ms)  SELECT "pipelines".* FROM "pipelines" INNER JOIN "states" ON "states"."pipeline_id" = "pipelines"."id" INNER JOIN "items" ON "items"."state_id" = "states"."id" WHERE "items"."name" = $1 AND "pipelines"."id" = $2 LIMIT $3  [["name", "Lotem"], ["id", "123"], ["LIMIT", 1]]

but once I call states from pipeline it generates new query without limitation:
puts @pipeline.states.inspect

State Load (0.4ms)  SELECT "states".* FROM "states" WHERE "states"."pipeline_id" = $1 /* loading for inspect */ LIMIT $2  [["pipeline_id", "123"], ["LIMIT", 11]]

I'm expecting that it should grab states from collection it already has loaded,
am I missing something ?


Answer:

but once I call states from pipeline it generates new query without
limitation

yeah, that's how joins work, it doesn't do more than that so the docs even don't bother adding more information. If you want to access the states within a single query (really it'll end up being 2 queries) you could use includes instead;
ActiveRecord::QueryMethods#includes;

Specify relationships to be included in the result set. It allows you
to access the address attribute of the User model without firing an
additional query.

and your query would slightly change to;
Pipeline
  .includes(states: :items)
  .where(items: { name: "Lorem" })
  .find('123')

The fact that invoking states on a Pipeline instance makes a new query is because you're invoking an instance method on that object which by definition makes a new query. Active Record won't know that you're referring to something that was already created in the query unless is specified otherwise (by using a custom select clause or similar).

Notice
Pipeline.joins(states: :items).where(items: { name: "Lorem" }) is the same as Pipeline.joins(states: :items).where(states: { items: { name: "Lorem" } }), you don't need to nest items under states.
Question: When injecting the DbContext using DI and using its private field in a query, should you still use the "using" scope?

I wanted to know if when you inject your DbContext with DI in a class, within the methods calling that context, should you use the using scope as well ? Or does DI knows about disposal after the method has been executed and/or does transient by default and it's safe ?


Answer:

When you inject a DbContext using dependency injection (DI), you generally don't need to use the using scope explicitly within the methods calling that context.
In the case of a transient registration for your DbContext, a new instance of the context will be created for each method call, and the DI container will automatically dispose of it once the method execution is complete. Therefore, you don't need to manually dispose of the context using the using statement.

 Microsoft Docs
Question: How can I generate signed URLs for accessing Firebase Storage images?

I am making a web service with sveltekit and firebase.
By the way, when users save images on firebase storage and other users try to use these images, I want to create a signed url and show it on the page to prevent Hotlink.
I searched and found that there is a function called getSignedUrl that generates a signed url, but there is no official document page that describes it in the firebase document.
Where can I get some example functions or information related to this?


Answer:
The Firebase SDK for Cloud Storage uses a different type of URL, called a download URL. You can generate a download URL by calling getDownloadURL with/on a reference to the file, as shown in the documentation on downloading data through a URL.
Question: ngx-image-cropper , roundCropper = "true" not working , its showing this error - Type 'string' is not assignable to type 'boolean'

<image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4"
    format="jpg" (imageCropped)="imageCropped($event)" roundCropper = "true">
</image-cropper>

[screenshot attached for your reference]
I used roundCropper = "True". But its not working and throwing the error:

Type 'string' is not assignable to type 'boolean'.

If a try to run the same code on stackblitz then its working. I have also tried it with roundCropper = true , but its giving same error.
I want to use round cropper in my ngx-image-cropper.


Answer:
Try to surround roundCropper with []
[roundCropper] = "true"
Question: Plotly: auto resize height

I am creating a bar graph using plotly express inside dash application. The graph is getting displayed but I am having an issue with height.Currently I am using default height and width.
Now for eg:

dataframe having field column contain 3 entires, the graph looks ok.

dataframe having field column contain 10 entires, the bar width is reduced auto and height remains the same and graph looks congested and hard to read.


figure = (
    px.bar(
        data_frame=dataframe,
        x="size",
        y="field",
        title="Memory Usage",
        text="size",
        # width=400,
        # height=400,
        orientation="h",
        labels={"size": "size in byte(s)"},
        template=template,
    ).update_traces(width=0.4)
    .update_layout(autosize=True)
)
        
dcc.Graph(id="memory_bar", figure=figure, className="dbc")

Is it possible depending on number of entires, the height can be auto-resized? Also I am using orient as horrizontal. I tried autosize=true but got no effect on height it remains same.


Answer:
It is possible to define a dynamic width and height based on the dataframe:

The number of categories can be found with dataframe['field'].nunique() (assuming you are using pandas). It will impact the height of the figure (since the bar chart is horizontal)
The number of entries can be found with dataframe.shape[0] and will impact the width of the figure. You could be more precise if you use dataframe.groupby("field").count()["size"].max() instead. It returns the maximum entry per category.

Then, we can define two methods for computing height and width of the figure:
def num_fields_based_height(num_fields: int) -> int:
    padding = 150 # arbitrary value depending on legends
    row_size = 100 # arbitrary value
    return padding + row_size * num_fields

def num_entries_based_width(num_entries: int) -> int:
    padding = 150 # arbitrary value depending on legends
    entry_size = 100 # arbitrary value
    return padding + entry_size * num_entries

Then call this methods when declaring the figure:
figure = (
    px.bar(
        data_frame=dataframe,
        x="size",
        y="field",
        title="Memory Usage",
        text="size",
        width=num_entries_based_width(dataframe.shape[0]),
        height=num_fields_based_height(dataframe['field'].nunique()),
        orientation="h",
        labels={"size": "size in byte(s)"},
    )
)

Now you need to find the right parameters (padding, entry_size, row_size) for your scenario.
Question: Rendering a Polygon in Pyglet using GL_TRIANGLES - KeyError 'v' Error

I am trying to render a polygon using the GL_TRIANGLES mode for pyglet.graphics.draw but have been running into issues.
I have been attempting to render it like I've seen people do in many other places
def draw(self):
    pyglet.graphics.draw(
       size=int(len(self.coords) / 2), 
       mode=pyglet.gl.GL_TRIANGLES,
       position=('v2f', self.coords),
    )

but have been running into the following error:
  File "C:\Python311\Lib\site-packages\pyglet\graphics\__init__.py", line 52, in draw
    gl_type = vertexdomain._gl_types[fmt[0]]
              ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
KeyError: 'v'

Did the usage change? Not sure exactly what I'm doing wrong here.


Answer:
v2f is the old format specification. In Pyglet Version 2.0, this has changed. See the documentation of draw(size, mode, **data). The first parameter is the number of vertices and each vertex has to have 3 components. The format is just f for float. e.g.:
self.coords = [x0, y0, z0, x1, y1, z1, ...]

pyglet.graphics.draw(
    size = len(self.coords) // 3,
    mode = pyglet.gl.GL_TRIANGLES,
    position = ('f', self.coords)
)

Note that this will draw only black triangles. Set the colors  attribute to draw a colorful shape.
Minimal example:

import pyglet

window = pyglet.window.Window(800, 600)

vertices = [100, 100, 0, 300, 100, 0, 200, 300, 0]
colors = [255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]

@window.event
def on_draw():
    window.clear()
    pyglet.graphics.draw(
        size = 3, 
        mode = pyglet.gl.GL_TRIANGLES, 
        position = ('f', vertices),
        colors = ('Bn', colors))
    
pyglet.app.run()
Question: Switching between Tkinter screens with withdraw() method on button click

Everything here works just fine but I haven't found a way to make it so that when I press the start button   it withdraws the Main Menu screen and displays the next one. It already creates the second screen when I run the code and it withdraws the MainMenu Screen before I even click the start button.
https://replit.com/@AbdullahKaran/ConfusedSophisticatedFolders#main.py


Answer:
work on how you ask questions, as this can lead to your account being blocked. I've seen this happen before, so it's good advice.
Now, you can do this by using the tkraise() method of the Frame widget. To learn more, please visit this website: https://www.pythontutorial.net/tkinter/tkraise/
Question: Dependent names vs non-dependent names

In the following example:
template<typename T>
struct MyList {
    typedef std::list<T> type1;
};

template<typename T>
class MyList2 {
    typename MyList<T>::type1 type2;
};

I thought that both type1 and type2 are dependent name since both of their types depend on the template parameter. However, why is the first one considered non-dependent since I can use typedef with it?


Answer:
A dependent name is, in C++ terms, a name whose grammatical properties are dependent on a template parameter.
Names can mean a lot of different things in C++, and the grammatical location where a name can be used depends on certain properties of that name. In order to understand what X x; is trying to do, the compiler needs to know what X is at this point in the program. If X names a type, then this is declaring a variable named x. The compiler doesn't need to know everything about X, but grammatically, in order to even begin to make sense of this text, the compiler does need to know that X here names a type.
std::list is the name of a class template; the compiler can easily see that because that's how it is declared. It doesn't need to have the body of the declaration; template<typename T> class list; is sufficient. std::list<T> is an instantiation of a class template, so just from the declaration, the compiler knows that this is the name of a type.
However, MyList<T>::type1 now requires more than just the declaration of the MyList template. It requires actually instantiating that template. And if T is itself a template parameter of the current code (as is the case for MyList2), then instantiation at the point of initially compiling the code is impossible. That instantiation must be delayed until MyList2 is itself given a concrete T to work with.
But the compiler still has to make sense of this code: typename MyList<T>::type1 type2;. And to do that, it needs some idea of what MyList<T>::type1 actually is. Without instantiating MyList<T>.
Which is why you have to tell it that it is a typename.
Question: handling 401 in angular, how does pipe work really?

I am using Angular 14 and making a post request to my json server using the pattern like this:
myApiCall(data:any): Observable<any> {
  return this.http.post<any>(url, data).pipe(catchError(this.handleError));
}

( as specified in https://angular.io/guide/http)
And then wanted to add 401 (unauthorized) handling to handleError
so I added this block
  if (error.status===401){//UnAthorized
    this.router.navigate(['login']);
  }

to my handleError like so:
private handleError(error: HttpErrorResponse) {
  if (error.status===401){//UnAthorized
    this.router.navigate(['login']);
  }
...
  return throwError(
    () => new Error('Something bad happened; please try again later.')
  );

}
I can see in debugger that this.router.navigate(['login']); is hit, but it does not navigate to the login screen.  same code does work in another place.
The error in chrome console is :
ERROR TypeError: Cannot read properties of (has file and line see below for details) undefined (reading 'router')
    at handleError (line where this.router.navigate(['login']); is)
    at catchError.js:10:39
    at OperatorSubscriber._error (OperatorSubscriber.js:23:21)
    ...

The top in call stack in the error is the .subscribe after myApiCall...
So what happens to handleError when I call
this.router.navigate(['login']);

Does it cause a return? And if so what gets returned ?
UPDATE
After Igor's suggestion of adding
return of([]) 

AND declaring handleError with ()=>{} syntax instead of normal, it worked.
I wonder why the second part is needed. I still suspect it has something to do with how pipe works.
This works:
private handleError = (error: HttpErrorResponse) => { 
  if (error.status===401)//UnAthorized
  {
    this.router.navigate(['login']);
    return of([]);
  } 
  ...
  return throwError(
    () => new Error('Something bad happened; please try again later.')
  );  
}

This does not
private handleError(error: HttpErrorResponse){ 
  if (error.status===401)//UnAthorized
  {
    this.router.navigate(['login']);
    return of([]);
  } 
  ...
  return throwError(
    () => new Error('Something bad happened; please try again later.')
  );  
}

After this.router.navigate instead of hitting return, control is transferred to the caller that results in an error that mentions router.
Why?
SECOND UPDATE:
Actually the first part (return of...) is not necessary to make it work, only the second (making it a lambda expression) is enough.


Answer:
Try this:
myApiCall(data:any): Observable<any> {
  return this.http.post<any>(url, data).pipe(
    catchError((err) =>
        if (err.status===401){
          // Redirect if unhautorized
          this.router.navigate(['login']);
        }
        ...
    );
}

Note the lambda syntax of the error handler declaration. It is required in order to pass in the context (this). Without it the 'router' is not known hence the error. More details here
Question: How to create a spatial gridlines using Latitude and Longitude in R

How to create a gridline of 7*7 sqkm using Latitude and Longitude values. These values should be the centroid value of a single square in the grid. I am not sure if I am doing it in the right way. I tried st_make_grid from sf (Simple Features) library but that shows me an empty plot.
MyGrid <- st_make_grid(DF, cellsize = c(0.07, 0.07), square = TRUE, crs = 4326) 

Below is my example DF
DF <- structure(list(lat = c(43.25724, 43.25724, 43.25724, 43.25616, 
43.25616, 43.25616), lon = c(-96.01955, -95.98172, -95.92336, 
-96.40973, -96.25733, -96.17735)), class = "data.frame", row.names = c(NA, 
6L))

## > DF
##        lat       lon
## 1 43.25724 -96.01955
## 2 43.25724 -95.98172
## 3 43.25724 -95.92336
## 4 43.25616 -96.40973
## 5 43.25616 -96.25733
## 6 43.25616 -96.17735

Thanks


Answer:
from the documentation of st_make_grid:

Create a square or hexagonal grid covering the
bounding box of the geometry of an sf or sfc object


so you need to convert your dataframe of point coordinates to an sf-object "the_points" (and reproject to a projection accepting metric length units):

library(sf)

the_points <- 
    st_sf(geometry = DF[c('lon', 'lat')] |>
              as.matrix() |>
              st_multipoint() |>
              st_sfc() |>
              st_cast('POINT'),
          crs = 4326 ## geographic data (in degrees)
          ) |>
    ## convert to projected coordinates (to specify dimensions in m
    ## take Google Mercator as first guess (EPSG-code 3857)
    st_transform(3857)


create grid (note that your points have only about 100 m latitudinal range):

the_grid <- 
    st_make_grid(n = c(10, 1), cellsize = 7e3 ## 7000 km)


inspect result:

plot(the_grid)
plot(the_points, add = TRUE)
Question: Efficient way to change the class of several matrices in R

I have several matrices and I would like to apply something like
class(matrix) <- "numeric" to all of them at once, i.e. the class of all matrices should be changed to numeric.
Do you know how to do this?
dput(matrix[1:3,]) results in structure(c(285.789361223578, 282.564165145159, 273.633228540421,  256.789452806115, 260.808130130172, 241.718192100525, 266.765343174338,  267.881099879742, 250.710165724158, 284.365977942944, 281.670583188534,  268.735618144274, 264.118778035045, 262.856532484293, 254.31867428124,  286.250801086426, 284.585711210966, 268.984649181366, 286.17267370224,  284.429456442595, 267.478255555034, 275.10055847466, 274.141056537628,  259.477523118258, 246.454664766788, 252.470473349094, 232.699362188578,  284.998321458697, 283.73363442719, 269.555955678225, 0, 0, 0), dim = c(3L,  11L), dimnames = list(NULL, c("", "", "", "", "", "", "", "",  "", "", "vec")))


Answer:
In this examples all matrix variables of the current environment are converted to numeric.
See the warning in the case where matrix cannot be converted to numeric.
var1 <- matrix(1:10, 5, 2)
var2 <- matrix(as.character(5:13), 3,3)
var3 <- letters[1:5]
var4 <- matrix(letters[1])

print(sapply(mget(ls()), typeof))
#>        var1        var2        var3        var4 
#>   "integer" "character" "character" "character"

for (i in ls()[sapply(mget(ls()), is.matrix)])
  assign(i, as.numeric(get(i)))
#> Warning in assign(i, as.numeric(get(i))): NAs introduced by coercion

print(sapply(mget(ls()), typeof))
#>           i        var1        var2        var3        var4 
#> "character"    "double"    "double" "character"    "double"

Created on 2023-06-03 with reprex v2.0.2