satoshi-2000/llms-suitable huggingface dataset:
Question: use surface pressure to mask 4D netcdf variable

I've merged a 3D surface pressure field (ERA5, converted from Pa to hPa, function of lat,lon and time) with a 4D variable which is also a function of pressure levels (lat,lon,time,level).
So, my netcdf file has two fields, Temperature which is 4D:
float t(time, level, latitude, longitude)

surface pressure, which is 3d:
float sp(time, latitude, longitude)

The pressure dimension "level" is of course a vector:
int level(level)

What I want to do is make a mask for temperature for all locations where the pressure exceeds the surface pressure.
I know how to use nco to make a mask using a simple threshold:
 ncap2 -s 'mask=(level>800)' t_ps.nc mask.nc

But of course when I try to use the surface pressure
ncap2 -s 'mask=(level>sp)' t_ps.nc mask.nc 

I get the error
ncap2: ERROR level and template sp share no dimensions

I think what I need to do is make a new variable like "level3d" which duplicates the pressure "level" to be a function of lat and lon, which I can then use to efficiently make the mask, yes?  But I'm not sure how to do this with a dimension (I thought about cdo enlarge but couldn't get it to work).
By the way, instead of posting the data, this is the python api script I used to retrieve it
import cdsapi
c = cdsapi.Client()
c.retrieve(
    'reanalysis-era5-single-levels-monthly-means',
    {
        'format': 'netcdf',
        'product_type': 'monthly_averaged_reanalysis',
        'variable': 'surface_pressure',
        'year': '2020',
        'month': '03',
        'time': '00:00',
    },
    'ps.nc')

c.retrieve(
    'reanalysis-era5-pressure-levels-monthly-means',
    {
        'format': 'netcdf',
        'product_type': 'monthly_averaged_reanalysis',
        'variable': 'temperature',
        'pressure_level': [
            '1', '2', '3',
            '5', '7', '10',
            '20', '30', '50',
            '70', '100', '125',
            '150', '175', '200',
            '225', '250', '300',
            '350', '400', '450',
            '500', '550', '600',
            '650', '700', '750',
            '775', '800', '825',
            '850', '875', '900',
            '925', '950', '975',
            '1000',
        ],
        'year': '2020',
        'month': '03',
        'time': '00:00',
    },
    't.nc')



Answer:
Your diagnosis of the NCO behavior is essentially correct. The "broadcast"
ncap2 -s 'mask=(level>sp)' t_ps.nc mask.nc

fails because level and sp are arrays (not scalars) that share no dimensions. The fix would be to create and use a temporary 3D version of level with something like
ncap2 -s 'level_3D[level,latitude,longitude]=level;mask=(level_3D>sp)' t_ps.nc mask.nc
Question: How to set invert_if_negative to fill bars to a solid color in python xlswriter

I am making graphics on excel from python using xls writer and want to make a graphic with green colored bars for positive values, and red for negative.
Current code seems like this:
chart3 = workbook.add_chart({'type': 'column'})
chart3.add_series({
    'values': '=Summary!$W$2:$W$76',
    'categories': '=Summary!$A$2:$A$76',
    'gap': 4,
    'line': {'width': 1},
    'name': '=Summary!$W$1',
    'fill':   {'color': 'green'},
    'invert_if_negative': True
})

It differientiates positive and negative values in the graph but the negative ones are just no-colored. Is there a way to make the inverted color to be red?
Already tried with other properties like inverted_color or any syntax like that but does not work


Answer:
You will need version >= 3.1.1 of XlsxWriter which supports the invert_if_negative_color parameter:
from xlsxwriter import Workbook


workbook = Workbook("chart.xlsx")

worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})

worksheet.write_column("A1", [3, 2, -3, 4, -2])

chart.add_series(
    {
        "values": "=Sheet1!$A$1:$A$5",
        "fill": {"color": "green"},
        "invert_if_negative": True,
        "invert_if_negative_color": "red",
    }
)

worksheet.insert_chart("C1", chart)

workbook.close()


Output:
Question: Custom CSS drop caps in Wordpress 6.2.2 with Twenty Twenty Three theme

I'm trying to do drop caps in the Twenty Twenty-Three theme on WordPress 6.2.2.
All the docs I find when I google it are for older versions of WordPress, and possibly on an older theme. It used to be easy, but I can't find relevant docs for how to do this with the Twenty Twenty-Three theme.
And following on from that, how do I add custom CSS to use a different font for the drop caps?
I have a couple of older posts from an earlier version of WP that have drop caps and I used to have them styled via a child theme I was using, but I upgraded to the Twenty Twenty Three theme and I lost all my customisations.
I've added the following code via the "Tools > Theme file editor", but it doesn't seem to be working.
p.has-drop-cap:not(:focus)::first-letter
{
  font-family: 'Fredericka the Great', cursive;
}



Answer:
Neither TwentyTwentyTwo nor TwentyTwentyThree currently support dropCaps. Since the layout looks undesirable on certain user systems, it was agreed that dropcap support is not mandatory for either theme. Read more - WordPress issues: https://github.com/WordPress/twentytwentytwo/issues/180
But there's a workaround available. Since you have to touch the theme core files, the use of a child theme is probably not a bad idea. Otherwise, adjustments could be overwritten when updating.
The workaround was first pointed out in a comment by @colorful-tones a user on GitHub, in this thread. The related CSS is from @justintadlock, another GitHub user, you can read more here.
So here are the steps you need to take to enable dropCap support:

Since you are using the theme file editor, go there and open       theme.json.
At about line 109, under typography, change the value for dropCap from false to true.
Save the file.
Open the theme's style.css and add:

.has-drop-cap:not(:focus)::first-letter {
    font-family: var( --wp--custom--drop-cap--typography--font-family, inherit );
    font-size: var( --wp--custom--drop-cap--typography--font-size, 5.5em );
    font-weight: var( --wp--custom--drop-cap--typography--font-weight, 700 );
    font-style: var( --wp--custom--drop-cap--typography--font-style, normal );
    line-height: var( --wp--custom--drop-cap--typography--line-height, .85 );
    margin: var( --wp--custom--drop-cap--spacing--margin, 0.05em 0.1em 0 0 );
    padding: var( --wp--custom--drop-cap--spacing--paddig, 0 );
}


Save the file.

NOTE: If you want to use a custom font you may have to add your font to the typography section in theme.json. A support topic from WordPress.org could be helpful hereby. You can also try to replace all variables directly in the CSS part with your own values. But I'm sorry I can't remember if it worked like that, because I used this workaround only once and it was some time ago and the page doesn't exist like that anymore. You'll just have to test it yourself.
Finally, don't forget to properly include your Fredericka the Great font into Wordpress.
Hope this works for you.
Question: Axis labeling for subplots

The following code generates this image 
I want the "y"-axis label to be "Space" and the "x"-axis label to be "time" for the left subplot. However, I am failing to achieve this. Why does my plotting code not do as I desire?
p1 = surface(sol.t, x, z, xlabel="Time", ylabel="Space", zlabel="|u|²", colorbar = false)
p2 = contourf(sol.t,x,z, xlabel="Time", ylabel="Space")
plt = plot(p1,p2,layout=(1,2), size=(1200,800))


using DifferentialEquations, LinearAlgebra, Plots, SparseArrays
plotlyjs()

N₁=31 # Number of waveguides / size of solution vector
γ=1  # Nonlinear term strength parameter
h=1 # Grid spacing 

centerGrid  = (N₁-1)/2;
x = -centerGrid:centerGrid;

# Coefficient matrix of second-order centered-difference operator (δ²u)ₙ
M           = spdiagm(-1 => fill(1,N₁-1), 0 => fill(-2,N₁), 1 => fill(1,N₁-1))
M[N₁,1]     = 1; # Periodic boundary conditions
M[1,N₁]     = 1;

# RHS of DNLS. The solution vector u is a N₁x1 complex vector
g₁(u,p,t)   = 1*im*(p[1]*M*u + @.(γ*((abs(u))^2).*u) )

# Julia is explicitly typed (e.g, cannot have Int and Complex in same array) and so we must convert the object containing the initial data to be complex
u0  = Complex.(sech.(x))

tspan = (0.0,200)
prob = ODEProblem(g₁,u0,tspan, [h])
sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)

z= [abs(sol.u[i][j])^2  for j=1:N₁, i=1:size(sol)[2]] # |u|²

p1 = surface(sol.t, x, z, xlabel="Time", ylabel="Space", zlabel="|u|²", colorbar = false)
p2 = contourf(sol.t,x,z, xlabel="Time", ylabel="Space")
plt = plot(p1,p2,layout=(1,2), size=(1200,800))



Answer:
Setting custom axis labels for 3d plots doesn't work with Plots and plotlyjs() backend. Only with GR backend your labels are displayed.
You can try this version using PLotlyJS.jl instead Plots.jl:
fig=make_subplots(rows=1, cols=2, specs =[Spec(kind="scene") Spec(kind="xy")], 
                  horizontal_spacing=-0.1, column_widths=[0.65, 0.35])
add_trace!(fig, PlotlyJS.surface(x=sol.t, y=collect(x), z=z', showscale=false), row=1, col=1)
add_trace!(fig, PlotlyJS.contour(x=sol.t, y=collect(x), z=z), row=1, col=2)
relayout!(fig, template=templates["plotly_white"], font_size=11,
                width=1000, height=600, scene=attr(xaxis_title="Time", yaxis_title="Space", 
                zaxis_title="|u|²", camera_eye=attr(x=1.8, y=1.8, z=1)),
                xaxis2_title="Time", yaxis2_title="Space",  margin_l=15) 
display(fig)
Question: 'newEmail' box that comes with identity is autopopulating and I can't stop it

I have created a website and included identity for logging in. On the manage your account page, the new email box keeps autopopulating and I can't figure out how to stop it.

I have tried to add the 'autocomplete=off' to the  tag (see below code) but it still populates.
@page
@using FarmersPortal.Areas.Identity.Pages.Account.Manage;
@model EmailModel
@{
    ViewData["Title"] = "Manage Email";
    ViewData["ActivePage"] = ManageNavPages.Email;
}

<style>
    body {
        background-image: url('http://10.48.1.215/PORTAL/hero-range-1.jpg');
        height: 100%;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
        /*        background-color: white;*/
    }
</style>

<h3 style="color:white">@ViewData["Title"]</h3>
<partial name="_StatusMessage" for="StatusMessage" />
<div class="row">
    <div class="col-md-6">
        <form id="email-form" method="post">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-floating input-group">
                <input asp-for="Email" class="form-control" disabled />
                <div class="input-group-append">
                    <span class="h-100 input-group-text text-success font-weight-bold">✓</span>
                </div>
                <label asp-for="Email" class="form-label"></label>
            </div>


            <div class="form-floating">
                <input asp-for="Input.NewEmail" class="form-control" autocomplete="off" aria-required="true" />
                <label asp-for="Input.NewEmail" class="form-label"></label>
                <span asp-validation-for="Input.NewEmail" class="text-danger"></span>
            </div>
            <button id="change-email-button" type="submit" asp-page-handler="ChangeEmail" class="w-100 btn btn-lg btn-primary">Change email</button>
        </form>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}



Answer:
asp-for sets the id, name and validation related attributes, and it also sets the value of the input element if there is already a value within the model passed to the view.
From your code, You are using:
<input asp-for="Input.NewEmail" class="form-control" autocomplete="off" aria-required="true" />

to input the value of Input.NewEmail, I think before you render this view, Input.NewEmail already has the value, asp-for will get this value and set value="xxx" attribute in input tag.
So if you don't want show the value, You can just use name property instead of asp-for, Change your code to:
<input name="Input.NewEmail" class="form-control" autocomplete="off" aria-required="true" />

Then when render this view, Input tag will show nothing.
Question: stick footer to bottom if actual page height is greater than html height

I have a situation where I use several sliders on the page due to which the actual height of the page changes
Let's say my html height is 600px but due to some sliders the actual page height is 1000px
And because of this, when I try to stick the footer to the bottom using position: absolute and bottom: 0, I have it placed at the end of the html height
I used an example to show how everything looks like for me
If I use position: relative then on other pages where the height is small, it will not be at the bottom
How can I stick the footer to the bottom of the page in this case?
I have also tried wrapping the entire html content in a class .wrapper { height: 100%; display: flex; flex-direction: column; } and for the footer use position: relative and margin-top: auto
This kind of helped, but then there were problems with the blocks that come after the html, they lost their width


html {
  height: 500px;
}

.main-content {
  padding: 200px;
  text-align: center;
}

.content {
  padding: 300px;
  text-align: center;
}

.footer {
  padding: 40px 0;
  position: absolute;
  width: 100%;
  bottom: 0;
  text-align: center;
  background: gray;
}
<html>
<div class="main-content"> MAIN CONTENT</div>
<div class="content">CONTENT</div>
<footer class="footer">FOOTER</footer>
</html>





Answer:
You can use flexbox. Uncomment height property in body to see the changes.
Check the elements html, body, main and footer in the code below.
Resources: 
CSS Tricks | Flexbox 
CSS Tricks | Flexbox and Auto Margins 
Dev | Stick Footer to The Bottom of The Page


* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  /*height: 1000px;*/
}

header {
  height: 50px;
  background-color: cyan;
}

main {
  flex: 1;
}

footer {
  margin-top: auto;
  height: 70px;
  background-color: red;
}
<html>
  <body>
    <header>Header</header>
    <main>Main</main>
    <footer>Footer</footer>
  </body>
</html>
Question: guard/if let in Java - declare a property or an object if it can be unwrapped

In swift there is the guard let / if let pattern allowing us to declare an object or a property only if it can be unwrapped.
it works a follow:
func getMeaningOfLife() -> Int? {
    42
}

func printMeaningOfLife() {
    if let name = getMeaningOfLife() {
        print(name)
    }
}

func printMeaningOfLife() {
    guard let name = getMeaningOfLife() else {
        return
    }

    print(name)
}

My question here is: Is there a Java version of it ?


Answer:
The answer is No.
Apparently this syntax also exists in Clojure and according to this Stack Overflow answer there is no way to declare a property if it can be unwrapped in Java.
Question: Powershell GUI, How to take password input without exposing

I have a situation I am writing a powershell GUI.
I need to take the password in a secure input.. How can I do it ?
The passwd input need to be secured in the window
below is my code

$Passwd                         = New-Object system.Windows.Forms.TextBox
$Passwd.multiline               = $false
$Passwd.width                   = 150
$Passwd.height                  = 20
$Passwd.location                = New-Object System.Drawing.Point(169,26)
$Passwd.Font                    = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Passwd.ForeColor               = [System.Drawing.ColorTranslator]::FromHtml("#7ed321")
$Passwd.BackColor               = [System.Drawing.ColorTranslator]::FromHtml("#000000")

this is the code
the passwd input nee to be secured input ?


Answer:
You need to set UseSystemPasswordChar to $true:
$Passwd.UseSystemPasswordChar = $true
Question: Banno External Plugin S3 Hosting Question

I am developing 2 plugins for Banno and have a hosting question.
My client will be hosting the plugins on S3. Can I use 1 bucket for both plugins or will they each need a bucket?
Thank you.
I haven't uploaded anything to S3 yet.


Answer:
We don't have material specific to Amazon Web Services (e.g., S3) but here's some general guidance which may be helpful.
No matter what, you'll need to make sure that your plugin's content is hosted by your public-facing web server. This means your web server must be accessible via the internet and cannot require the user to be on a specific network or VPN.
See these resources for more info:

Plugin Framework / Architecture / Hosting
Plugin Framework / Guides/ Designing and Developing Plugins

The gist is that how you build your plugin's web service is at your discretion.

Whether you have separate S3 buckets or a single S3 bucket, that's up to you to decide what's best for your plugin.
Question: Link list sidebar widget remove button not working in jquery

I am creating a link list widget. Whenever we clicked on Title button, it adds a list with add link option. Everything is working fine but whenever I am trying to click the remove title button. The button is not working anymore. Where the alert is working and logs are showing also in console but the action is not working. Can you please check?
Code Pen Codepen Reference Link


Answer:
At line 23 you are only selecting a parent HTML element when the remove-title button is clicked, but doing nothing with it.


if ($(".remove-title").length) {
  $("body").on("click", ".remove-title", function() {
    console.log("clicked");
    $(this).parents(".btn-options");
  });
}



First you should make sure you're not deleting the only section left. If so, the .add-title button is triggered first.


if ($(".remove-title").length) {
  $("body").on("click", ".remove-title", function() {
    console.log("clicked");
    var $this = $(this);
    var parent = $this.parents(".title-area");
    if (!parent.siblings(".title-area").length) {
      $this.siblings(".add-title").trigger("click");
    }
    var title = parent.find("input.title-text").eq(0).val();
    var toast = parent.siblings(".title-area").find(".btn-toast");
    toast.show().html("Title removed: <span>" + title + "</span>")
      .delay(400).fadeOut("slow");
    parent.remove();
  });
}



As you can see, I've also added a "toast" element to the btn-options div to briefly display the title of the deleted section. You can find the rest of those changes here: Codepen
Question: What is the equivalent of add.classList in React for toggling visibility?

Adding and removing classes to elements in React
I’m a complete newb with React but basically I’ve been trying to make it so that a container goes from hidden to visible when you click a button.
Usually I’d just do an eventListner and add.classList or remove.classList but I can’t find the equivalent to that in react ?
I’ve tried figuring it out with useState and everything but I feel like I’m just overlooking something simple.
I would really appreciate some help it’s been like hours and my tiny brain is gonna explode


Answer:
I would recommend adding a condition to render the element/component instead of using classes.
const [visible, setVisible] = useState(false);

return (
  <div>
    <button onClick={() => setVisible(!visible)}>toggle</button>
    {visible && <span>hello</span>}
  </div>
);
Question: How do I prevent 'NotImplementedError' and 'TypeError' when using numeric aggregate functions in Pandas pivot tables with string columns?

I have tried severally to perform some numeric aggregation methods on numeric data with pandas. However, I have received a NotImplementedError, which then throws a TypeError, whenever I do so. I hypothesize that pandas is refusing to ignore the string columns when performing said numerical tasks. How do I prevent this?
Given a pivot table named matrix_data, and with pandas imported as pan:
  Account Number  Company      Contact Account Manager     Product  Licenses   
0         2123398   Google  Larry Pager    Edward Thorp   Analytics       150  
1         2123398   Google  Larry Pager    Edward Thorp  Prediction       150   
2         2123398   Google  Larry Pager    Edward Thorp    Tracking       300   
3         2192650     BOBO  Larry Pager    Edward Thorp   Analytics       150   
4          420496     IKEA    Elon Tusk    Edward Thorp   Analytics       300   

   Sale Price        Status  
0     2100000     Presented  
1      700000     Presented  
2      350000  Under Review  
3     2450000          Lost  
4     4550000           Won  

Trying to aggregate all numerical values by company:
pan.pivot_table(matrix_data, index = "Company", aggfunc="mean");

throws an exception like so:
NotImplementedError                       Traceback (most recent call last)
File ~\AppData\Roaming\Python\Python311\site-packages\pandas\core\groupby\groupby.py:1490, in GroupBy._cython_agg_general..array_func(values)
   1489 try:
-> 1490     result = self.grouper._cython_operation(
   1491         "aggregate",
   1492         values,
   1493         how,
   1494         axis=data.ndim - 1,
   1495         min_count=min_count,
   1496         **kwargs,
   1497     )
   1498 except NotImplementedError:
   1499     # generally if we have numeric_only=False
   1500     # and non-applicable functions
...
   1698             # e.g. "foo"
-> 1699             raise TypeError(f"Could not convert {x} to numeric") from err
   1700 return x

TypeError: Could not convert Larry PagerLarry PagerLarry Pager to numeric

dataframe.groupby(["col_name1"]).mean() will throw an identical error
I'm on windows 10, python 3.11, with pandas version 2.0.1. All this was performed on Jupyter Notebook with VScode


Answer:
This has been deprecated in Pandas 2.0. This is the warning pandas 1.5.3 gives:

FutureWarning: pivot_table dropped a column because it failed to
aggregate. This behavior is deprecated and will raise in a future
version of pandas. Select only the columns that can be aggregated.

You now have to select the specific columns you want to aggregate.
cols = ['Licenses', 'Sale Price']
pd.pivot_table(matrix_data, values=cols, index="Company", aggfunc="mean")
Question: Can I be guaranteed that a variable value will be passed along to a new running Task?

Can I assume the following code will always pass my assertions? I'm a worried about the index value. I'm not sure if the scoped value will be passed along to the Task.Run lambda expression. I think it will be scoped just like the attributesChunked value seems to be. But I'd like some confirmation.
var tasks = new List<Task>();
var attributes = new string[4]{ "att1", "att2", "att3", "att4" };
var chunkIndex = -1;
foreach (var attributesChunked in attributes.Chunk(2))
{
    var index = Interlocked.Increment(ref chunkIndex);
    tasks.Add(Task.Run(() =>
    {
        if (index == 0)
             Assert.Equal("attr1", attributesChunked.First());
        if (index == 2)
             Assert.Equal("attr3", attributesChunked.First());
    }
}
await Task.WhenAll(tasks);



Answer:
For each task you create, you are introducing a closure on the index variable declared in that iteration. So yes your Task will use the right value, as can be tested using following code:
static async Task Main(string[] args)
{
    var tasks = new List<Task>();
    var attributes = new string[4] { "att1", "att2", "att3", "att4" };
    var chunkIndex = -1;
    foreach (var attributesChunked in attributes.Chunk(2))
    {
        var index = Interlocked.Increment(ref chunkIndex);
        tasks.Add(Task.Run(async () =>
        {
            //simulate some work...
            await Task.Delay(50);
            Console.WriteLine($"index: {index}");
        }));
    }
    await Task.WhenAll(tasks);
}

The result:

index: 0
index: 1

Note that the sequence of the output is entirely dependent on the scheduling of the individual Tasks and cannot be predicted...
Useful reference: What are 'closures' in .NET?