satoshi-2000/llms-suitable huggingface dataset:
Question: x86 rep prefix with a count of zero: what happens?

What happens for an initial count of zero for an x86 rep prefix?
Intel's manual says explicitly it’s a while count != 0 loop with the test at the top, which is the sane expected behaviour.
But most of the many vague reports I’ve seen elsewhere suggest that there’s no initial test for zero so it would be like a countdown with a test at the end and so disaster if it’s repeat {… count —=1; } until count == 0; or who knows.


Answer:
Nothing happens with RCX=0; rep prefixes do check for zero first like the pseudocode says.  (Unlike the loop instruction which is exactly like the bottom of a do{}while(--ecx), or a dec rcx/jnz but without affecting FLAGS.)
I think I've heard of this rarely being used as an idiom for a conditional load or store with rep lodsw or rep stosw with a count of 0 or 1, especially in the bad old days before cmov.  (cmov is an unconditional load feeding an ALU select operation, so it needs a valid address, unlike rep lods with a count of zero.)  This is not efficient especially for rep stos on modern x86 with Fast Strings microcode (P6 and later), especially without anything like Fast Short Rep-Movs (Ice Lake IIRC.)
The same applies for instructions that treat the prefixes as repz / repnz (cmps/scas) instead of unconditional rep (lods/stos/movs).  Doing zero iterations means they leave FLAGS umodified.
If you want to check FLAGS after a repe/ne cmps/scas, you need to make sure the count was non-zero, or that FLAGS was already set such that you'll branch in a useful way for zero-length buffers.  (Perhaps from xor-zeroing a register that you're going to want later.)

rep movs and rep stos have fast-strings microcode on CPUs since P6, but the startup overhead makes them rarely worth it, especially when sizes can be short and/or data might be misaligned.  They're more useful in kernel code where you can't freely use XMM registers.  Some recent CPUs like Ice Lake have fast-short-rep microcode that I think is supposed to reduce startup overhead for small counts.
repe/ne scas/cmps do not have fast-strings microcode on most CPUs, only on very recent CPUs like Sapphire Rapids and maybe Alder Lake P-cores.  So they're quite slow, like one load per clock cycle (so 2 cycles per count for cmpsb/w/d/q) according to testing by https://agner.org/optimize/ and https://uops.info/.

What setup does REP do?
Why is this code using strlen heavily 6.5x slower with GCC optimizations enabled? - GCC -O1 used to use repne scasb to inline strlen.  This is a disaster for long strings.
Which processors support "Fast Short REP CMPSB and SCASB" (very recent feature)
Enhanced REP MOVSB for memcpy - even without ERMSB, rep movs will use no-RFO stores for large sizes, similar to NT stores but not bypassing the cache.  Good general Q&A about memory bandwidth considerations.
Question: Dictionary Comprehension within pandas dataframe column

Trying to match a dictionary item with a string value from another column.
sample data:
df =     A    B
     0  'a'  {'a': '2', 'b': '5'}
     1  'c'  {'a': '2', 'b': '16', 'c': '32'}
     2  'a'  {'a': '6', 'd': '23'} 
     3  'd'  {'b': '4', 'd': '76'}
     

I'm trying to get the following out:
Df =     A    B
     0   'a'  {'a': '2'}
     1   'c'  {'c': '32'}
     2   'a'  {'a': '6'}
     3   'd'  {'d': '76'}

I got this far not inside a dataframe:
d = {k: v for k, v in my_dict.items() if k == 'a'}

for a single line, but I couldn't get this to work and to be fair, I didn't expect it to work directly, but was hoping i was close:
Test_df['B'] = {k: v for k, v in test_df['B'].items() if k == test_df['A']}

I get the following error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What do I need to do to get this to work, or is there a better more efficient way?


Answer:
You can use a list comprehension with zip:
df['B'] = [{x: d[x]} for x, d in zip(df['A'], df['B'])]

Output:
   A            B
0  a   {'a': '2'}
1  c  {'c': '32'}
2  a   {'a': '6'}
3  d  {'d': '76'}
Question: How can I assert that the jest mocked module method was called?

How can I assert that the jest mocked module method was called?
E.g. in my .spec.js I have the following jest mocked module:
jest.mock('../../../../services/logs.service.js', () => ({
    log: jest.fn()
}));

Now I would like to assert the log method. I.e. something like this:
//the log was called twice with the text "foo"
expect(log).toHaveBeenCalledWith(2, "foo");

But I can not access the log. I tried putting the log initialization outside the jest mocked module, like so:
const log = jest.fn();
jest.mock('../../../../services/logs.service.js', () => ({
    log
}));

But I got the error:

The module factory of jest.mock() is not allowed to reference any out-of-scope variables.



Answer:
You can do the following:
JavaScript
import { log } from '../../../../services/logs.service.js';

jest.mock('../../../../services/logs.service.js', () => ({
    log: jest.fn()
}));

expect(log).toHaveBeenCalledWith(2, "foo"); // JavaScript

TypeScript
import { log } from '../../../../services/logs.service.js';

jest.mock('../../../../services/logs.service.js', () => ({
    log: jest.fn()
}));

const mockedLog = log as jest.MockedFunction<typeof log>;

expect(mockedLog).toHaveBeenCalledWith(2, "foo");
Question: Ionic app error: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have a mobile app developed in ionic capacitor. The backend to the app is a .net core web api deployed on amazon elastic beanstalk. I am getting CORS error** No 'Access-Control-Allow-Origin' header is present on the requested resource** when trying to access the back end using the app.
I have attempted to allow the API to be accessible by any consumer by allowing all origins. Is there need to configure anything on AWS Elastic bean?
var app = builder.Build();
app.UseCors(builder => builder
     .AllowAnyOrigin()
     .AllowAnyMethod()
     .AllowAnyHeader()
     );



Answer:

Log in to the AWS Management Console and navigate to the Elastic Beanstalk service.
Select your application and environment where the .NET Core Web API is deployed.
In the navigation pane, click on "Configuration."
Under the "Software" section, click on "Edit" for the "Environment properties."
Add a new property with the following details:

Name: ACCESS_CONTROL_ALLOW_ORIGIN
Value: * (or the specific origin you want to allow if you don't want to allow all origins)


Save the changes and wait for the environment to update.

Make sure to remove the CORS configuration you mentioned from your .NET Core Web API code, as the CORS handling will now be done by Elastic Beanstalk.
Question: Draw random numbers from a custom probability density function in Julia

I would like to draw random numbers from a modified exponential distribution:
p(x) = C * a * Exp[-(a*x)^b] with C=1/Gamma[1 + 1/b] for normalization.
How can I do this in julia? Unfortunately I have only little experience with Julia and no experiences with creating custom random numbers. I would be very grateful for any help.


Answer:
If I'm not mistaken, that is a p-Generalized Gaussian distribution, which has a rather efficient implementation in Distributions.jl:
using Distributions
mu = 0       # your location parameter
alpha = 1/a  # your scale parameter
beta = b     # your shape parameter
p = PGeneralizedGaussian(mu, alpha, beta)

Using the Distributions.jl API for univariate distributions, you can sample from this distribution by passing it to the exported rand method. Here is an example of how to sample five independent scalars from a PGeneralizedGaussian distribution with mu = 0, alpha = 1/2 and beta = 3:
julia> p = PGeneralizedGaussian(0, 1/2, 3);

julia> rand(p, 5)
5-element Vector{Float64}:
  0.2835117212764108
 -0.023160728370422268
  0.3075395764050027
 -0.19233721955795835
  0.21256694763885342

If you want to try to implement the distribution yourself, which I do not recommend unless you are doing this as an exercise in programming math in Julia, you need to define a type that holds the static parameters of the distribution (in your case, just the shape parameter and the scale parameter), then define and export the methods listed here to extend the Distributions.jl API to your custom distribution. In particular, you need to define:
struct MyDistribution <: ContinuousUnivariateDistribution
  # ... your distribution parameters here
end

rand(::AbstractRNG, d::MyDistribution) # sample a value from d
sampler(d::MyDistribution)             # return d or something that can sample from d more efficiently
logpdf(d::MyDistribution, x::Real)     # compute the log of the pdf of d at x
cdf(d::MyDistribution, x::Real)        # compute the cdf of d at x
quantile(d::MyDistribution, q::Real)   # compute the qth quantile of d
minimum(d::MyDistribution)             # return the minimum value supported by d
maximum(d::MyDistribution)             # return the maximum value supported by d
insupport(d::MyDistribution, x::Real)  # query whether x is supported by d

The documentation of the package is very good, so it's an excellent way to get your feet wet if you are trying to learn Julia.
Question: Border doesn't adapt after collapsing a column

For my main project, I'm trying to find a way to hide a column in JS. The following function :
function hide() {
    const table = document.getElementById('test');
    const cols = table.getElementsByTagName('col');
    cols[1].style.visibility = "collapse";
}

works great, but the borders don't move. Here's the problem :
 becomes 
How can I avoid this issue ?
EDIT : This works as intended on Chrome and Edge. Is this a bug for Firefox?
Full html is:


function hide() {
    const table = document.getElementById('test');
    const cols = table.getElementsByTagName('col');
    cols[1].style.visibility = "collapse";
}
table, tr, th, td {
    border: 1px solid;
    border-collapse: collapse;
}
<table id="test">
    <colgroup>
        <col><col><col>
    </colgroup>
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
    <tr>
        <td>un</td>
        <td>deux</td>
        <td>trois</td>
    </tr>
    <tr>
        <td>one</td>
        <td>two</td>
        <td>three</td>
    </tr>
</table>

<button onclick=hide()>Hide</button>





Answer:
To address this issue, you can use the border-spacing property instead of border-collapse. Modify your CSS as follows:
<style>
table {
    border-spacing: 0;
}

th, td {
    border: 1px solid;
    padding: 5px;
}
</style>
Question: TypeError: data type '>' not understood using dtype from numpy

first I saw similar questions but nothing helped me.
I'm trying to sort list of tuples, and convert the data types inside the tuple,
convert it according to a list of tuples I get.
for example, if I have a list of tuple, every tuple is built like
(ID,Grade,Height)

A = [(123,23,67),(234,67,45)]

and I have a list of type like that:
[(ID,int),(grade,'s15'),(height,float)]
now I read that 's15' is a dtype from bumpy, but I can't seem to use it.
I tried to copy from the docs:
import numpy as np
dt = np.dtype(('>14'))

but all I get is this error:
dt = np.dtype(('>14'))
TypeError: data type '>' not understood

the docs I copied from:
https://numpy.org/doc/stable/reference/arrays.dtypes.html
and is there a generic converter I can use to convert to any type I'm given?


Answer:
I think you maybe overlooked the documentation you are referring.
You used
dt = np.dtype(('>14'))

which is >14 (fourteen)...
But in fact the documentation clearly mentions
dt = np.dtype('>i4')

which is i4 not 1 (one)
Also based on the docs > or < specifies upper/lower bound for each dtype, for example >i would be big endian integer (see Endianess)
And the number after that would indicate number of bytes given to the dtype (see docs)
Finally the S indicates Zero terminated bytes
Based on your description, your teacher wants Upper endian ~128 bit Zero terminated bytes
Furthermore,
dt = np.dtype(('>S15'))

works fine.
I hope this fixes your issue
Question: Is there ST_Intersects alternative that allows two(or more) polygons to share sides

I am using ST_Intersects to check if two polygons intersect. Relevant part of my query is:
SELECT entity_number
FROM coordinates
WHERE ST_INTERSECTS($1, location)


It works well to determine if one polygon crosses the other's surface:

I expected ST_Intersects to return false when two polygons share sides, but it does not:

I read about other methods like ST_Covers, ST_Contains, ST_ContainsProperly, ST_Within ,ST_DWithin. But i am not sure which one suits my needs.
Is there any method that allows two polygons to share sides?


Answer:
You want ST_Overlaps:

Returns TRUE if geometry A and B "spatially overlap". Two geometries overlap if they have the same dimension, each has at least one point not shared by the other (or equivalently neither covers the other), and the intersection of their interiors has the same dimension. The overlaps relationship is symmetrical.
Question: React Router - How can I reuse my layout for the errorElement in the root route?

I'm using React Router v6 and following are my routes:
const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    errorElement: <ErrorPage />,
    children: [
      {
        index: true,
        element: <HomePage />,
      },
      {
        path: '/sign-up',
        element: <SignUpPage />,
      },
      {
        path: '/log-in',
        element: <LogInPage />,
      },
    ],
  },
]);

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement,
);

root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
);

The App component contains my app's layout and outputs the route elements using the Outlet component. But now if there's an error that bubbles up to the root route, then the ErrorPage gets displayed as expected, but it doesn't make use of the layout from App... So, how can I reuse my layout from App when the error page gets displayed?


Answer:
When there's an error it is kind of an either or kind of scenario. Either conditions are fine and the App component is rendered or there's an error condition and the ErrorPage component is rendered.
What you could do is to abstract the layout portion of the App component into a layout component on its own that can render either a passed children prop or the Outlet component for the nested route, and render it in App and also wrap the ErrorPage component.
Example:
const AppLayout = ({ children }) => (
  ...
  {children ?? <Outlet />}
  ...
);

const App = () => (
  ...
  <AppLayout />
  ...
);

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />, // <-- uses Outlet
    errorElement: (
      <AppLayout>     // <-- uses children
        <ErrorPage />
      </AppLayout>
    ),
    children: [
      {
        index: true,
        element: <HomePage />
      },
      {
        path: "/sign-up",
        element: <SignUpPage />
      },
      {
        path: "/log-in",
        element: <LogInPage />
      }
    ]
  }
]);
Question: How to fix a container at a particular spot on the screen

I'm learning flutter and I have made an app that looks like this:

I'm facing a problem as to how to fix the container fixed on a particular spot on the screen like it has to be aligned to the top center. Here's the problem I'm facing:

Here's the code:
class Program7 extends StatefulWidget {
  const Program7({super.key});

  @override
  State<Program7> createState() => _Program7State();
}

class _Program7State extends State<Program7> {
  double cHeightAndWidth = 300;

  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Container(
            height: cHeightAndWidth,
            width: cHeightAndWidth,
            decoration: BoxDecoration(
              color: Colors.purple,
            ),
          ),
          Column(
            children: [
              //A bunch of rows of buttons,
            ],
          ),
        ],
      ),
    );
  }
}


P.S.: I already tried to fix the container to the top center of another container using align but the purple color somehow bleeds out into the bigger container.


Answer:
The issue is using MainAxisAlignment.spaceAround,. It will use the free space and put half before and another half at end of the child.
You can use fixed gap for top(Container).
return SafeArea(
  child: Column(
    children: [
      SizedBox(height: 50),
      Container(
        height: cHeightAndWidth,
        width: cHeightAndWidth,
        decoration: BoxDecoration(
          color: Colors.purple,
        ),
      ),
      Spacer(), // or other widget
      Column(
        children: [
          //A bunch of rows of buttons,
        ],
      ),
    ],
  ),
);
Question: Find element by class under the same parent

Any particular reason about this isn't matching the element with that class?
I have checked a million times and can't see what is that I'm doing wrong.


$('.lnk-folder').click(function(e) {
  e.preventDefault();
  var header = $(this).parent('thead').find('.folder-header');
  console.log($(header));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<thead>
  <tr>
    <th colspan="10" style="padding:0px; font-size:120%;background-color:#ff0000;">
      <div style="float:left;min-width:20%;">
        <a style="color: #000" class="lnk-folder folder-close" data-hash="" href="#">
          <i class='fa fa-folder-open'></i> Folder 1
        </a>
      </div>
      <div style="float:left;height:26px;padding-left:10px;">
        <a href="#"><i class='fas fa-file-upload tooltip' style="color:#fff;"><span class="tooltiptext_m">New</span></i></a>
      </div>
    </th>
  </tr>
  <tr class="folder-header">
    <th colspan="2" style='background-color:#0c343d;vertical-align:middle;'> Name </th>
    <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Code </th>
    <th style='width:30%;background-color:#0c343d;vertical-align:middle;'> Act</th>
    <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Version</th>
  </tr>
</thead>





Answer:
parent() is your problem. It looks up the DOM exactly one level, to the parent element, but you need to go higher than that. To do so, use closest()


$('.lnk-folder').click(function(e) {
  e.preventDefault();
  var header = $(this).closest('thead').find('.folder-header');
  console.log($(header));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th colspan="10" style="padding:0px; font-size:120%;background-color:#ff0000;">
        <div style="float:left;min-width:20%;">
          <a style="color: #000" class="lnk-folder folder-close" data-hash="" href="#">
            <i class='fa fa-folder-open'></i> Folder 1
          </a>
        </div>
        <div style="float:left;height:26px;padding-left:10px;">
          <a href="#"><i class='fas fa-file-upload tooltip' style="color:#fff;"><span class="tooltiptext_m">New</span></i></a>
        </div>
      </th>
    </tr>
    <tr class="folder-header">
      <th colspan="2" style='background-color:#0c343d;vertical-align:middle;'> Name </th>
      <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Code </th>
      <th style='width:30%;background-color:#0c343d;vertical-align:middle;'> Act</th>
      <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Version</th>
    </tr>
  </thead>
</table>
Question: save multiple pdf pages with different sizes in Shiny R

Im developing a shiny app with several features. I added a button to download a single pdf file that contains many plots. I want to save those plots in individual pages but I want to choose the size of each pdf page. Is that possible?
This is he code that  have so far:
output$exportall<-downloadHandler(
filename="Allplots.pdf",
content=function(file){
  withProgress(message = 'Exporting', min=0,max=1, { 
    pdf(file,width=8,height=11)
    print(plot1())
    print(histogram())
    print(plots2())
    print(marrangeGrob(woodsbytimepoint(), nrow=2, ncol=1))
    print(digestion())
    print(map())
    print(marrangeGrob(allplots(), nrow=4, ncol=2, top=NULL))
    
  dev.off()
  })
 }
)

The code works fine and exports all the plots that I want. However, all pages in the pdf file are 8x11. Is there a way to speciffy the size of each page? for example I want the first plot to be 7x7 and all other 8x11.
Any ideas?


Answer:
Perhaps the simplest is to create separate PDFs (sized appropriately) and combine them with qpdf::pdf_combine.
file <- "file.pdf"
pdf(paste0(file, ".8x11"), width=8, height=11)
plot(disp ~ mpg, data = mtcars)
gg <- ggplot(mtcars, aes(disp, mpg)) + geom_point()
print(gg)
dev.off()
pdf(paste0(file, ".7x7"), width=7, height=7)
print(gg) # or anything else
dev.off()
qpdf::pdf_combine(paste0(file, c(".8x11", ".7x7")), file)
file.remove(paste0(file, c(".8x11", ".7x7")))

The resulting file.pdf pages:

If your sizes are not always in order (e.g., 8x11, 7x7, 8x11), you can either:

create three PDF files (would need an adjusted file name convention) and concatenate in order, or
create two PDF files (by dimensions), then also use qpdf::pdf_subset ... though since this creates new PDF files that you would then need to include in pdf_combine, it hardly seems the most efficient method.

I cannot test this, but I think this means your code should be
output$exportall<-downloadHandler(
filename="Allplots.pdf",
content=function(file){
  withProgress(message = 'Exporting', min=0,max=1, { 
    pdf(paste0(file, ".7x7"), width=7, height=7)
    print(plot1())
    dev.off()
    pdf(paste0(file, ".8x11"), width=8, height=11)
    print(histogram())
    print(plots2())
    print(marrangeGrob(woodsbytimepoint(), nrow=2, ncol=1))
    print(digestion())
    print(map())
    print(marrangeGrob(allplots(), nrow=4, ncol=2, top=NULL))
    dev.off()
    qpdf::pdf_combine(paste0(file, c(".7x7", ".8x11")), output=file)
  })
 }
)
Question: Why can I only print the text of a text file once?

I have written a little class which reads a text file and which have a method for printing the text (file.output()). For the first call it worked, but the second call of the method nothing is happening. I do not understand why, since I assume that the FOR-Loop does not change anything.
class Datei():
    def __init__(self, filename):
        self.fileobject = open(filename)
        
    def output(self): 
        for line in self.fileobject: 
            print(line.rstrip())
        
    
    def end(self): 
        self.fileobject.close()

file = Datei("yellow_snow.txt")
file.output()
print("second try")
file.output()

file.end()

I expected the text of the text file to be printed twice, but it is only printed once.


Answer:
When you read a file, you move a pointer through it, and it's now at the end - you can .seek(0) to get back to the start (or other positions, 0 is where you started from, which is the beginning if you're not in append mode)
with open(path) as fh:
    print(fh.tell())  # start of file
    print(fh.read())  # get everything and display it
    print(fh.tell())  # end of file
    fh.seek(0)        # go back to the beginning
    print(fh.tell())  # start of file
    print(fh.read())

More detail in Python Documentation 7.2.1. Methods of File Objects
Question: Reverse the content order of several columns (ideally in tidyverse)

Assuming the following data:
df <- data.frame(a = 1:3, b = c(1, 2, 6), c = c(4, 6, NA), d = c(6, NA, NA))

  a b  c  d
1 1 1  4  6
2 2 2  6 NA
3 3 6 NA NA

And what I want is:
  a b  c  d
1 1 6  4  1
2 2 6  2 NA
3 3 6 NA NA

I thought about some combination of across and rev, but my current attempts don't work.


Answer:
You can do the following:
pivot_longer(df, -a) %>%
  filter(!is.na(value)) %>%
  mutate(value=rev(value), .by=a) %>%
  pivot_wider(names_from = name, values_from = value)

Output:
      a     b     c     d
  <int> <dbl> <dbl> <dbl>
1     1     6     4     1
2     2     6     2    NA
3     3     6    NA    NA