Normal view

There are new articles available, click to refresh the page.
Today — 4 May 2024Main stream

individual gradients with torch.autograd.grad without sum over second variable

I have a sampled path of a stochastic process starting from an initial point:


class SDE_ou_1d(nn.Module):
    def __init__(self):
        super().__init__()
        self.sde_type = "into"
        self.noise_type = "diagonal"

    def f(self, t, y): #drift
        return -y

    def g(self, t, y): #vol
        return torch.ones_like(y)

t_vec = torch.linspace(0, 1, 100)  #time array
mySDE = SDE_ou_1d()

x0 = torch.zeros(1, 1, requires_grad=True).to(t_vec)
X_t = torchsde.sdeint(mySDE, x0, t_vec, method = 'euler')

and I would like to measure the gradient with respect to the initial condition using torch.autograd.grad(), and get an output with the same shape as X_t i.e. 100x1. This gives the change in the path at every time point


X_grad = torch.autograd.grad(outputs=X_t, inputs=x0,
                           grad_outputs=torch.ones_like(X_t),
                           create_graph=False, retain_graph=True, only_inputs=True, allow_unused=True)[0]

the issue is that the gradient is a sum over all values of t.

I can do this with a for loop, but it is very slow and not practical:

X_grad_loop = torch.zeros_like(X_t)

for i in range(X_t.shape[0]):  # Loop over the first dimension of X_t which is time
    grad_i = torch.autograd.grad(outputs=X_t[i,...], inputs=x0,
                                    grad_outputs=torch.ones_like(X_t[i,...]),
                                    create_graph=False, retain_graph=True, only_inputs=True, allow_unused=True)[0]
    X_grad_loop[i,...] = grad_i

is there a way to compute this gradient with torch.autograd.grad() and no loop? thanks

PostgreSql Row-Level Locks

I am trying to understand Postgresql Row-Level Locks could someone help me understand when to use each type of lock.

     FOR UPDATE; FOR NO KEY UPDATE; FOR SHARE; FOR KEY SHARE;

I tried to go over the documentation but still, I couldn't understand the difference and didn't know when to use what and how does it make a difference.

I am expecting someone could help me understand the use case of each lock and give me clarity on when to choose each.

Issue saving UUID in oracle database

I'm using oracle RDBMS 19.0.0.0.0 with NLS_CHARACTERSET AL32UTF8.

Java based application is saving uuid "a0089b95-9fa4-5ad6-8000-029e1fd30cf9" in database, its being saved as "Bᅰ089b95-9fa4-5ad6-8000-029e1fd30cf9".

The column where data is being saved is VARCHAR2(40).

When I directly execute query it is saved correctly.

Any ideas guys??

how to make a row in a matrix only go as long as the first number?

so i have this exercise on matrixes which needs to be done with two dimensional arrays. the first part was that you have n, which goes from 1 to 9. for each row, you need to output the muliplication table of that first number. so basically:

  • 1, 2, 3, 4, 5, 6, 7, 8, 9
  • 2, 4, 6, 8, 10, 12, 14, 16, 18
  • 3, 6, 9, 12, 15, 18, 21, 24, 27

and so on until 9. this part i solved the following way:

public static void main(String[] args) {
        int[][] column = new int[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 }, { 9 } };
        int[][] row = new int[][] { { 1, 2, 3, 4, 5, 6, 7, 8, 9 } };
        int[][] result = new int[column.length][row[0].length];
    
        for (int i = 0; i < column.length; i++) {
            for (int j = 0; j < row[0].length; j++) {
                for (int n = 0; n < column[0].length; n++) {
                    result[i][j] += column[i][n] * row[n][j];
                }
            }
        }
        System.out.println("Teilaufgabe a: " + "\r\n");
        for (int[] rowResult : result) {
            System.out.println(Arrays.toString(rowResult));
        }

    }

}

now my problem lies in the 2nd part of the exercise, where each line needs to be as long as the number of row[0], basically creating a stair structure.

it should look like this:

  • 1
  • 2, 4
  • 3, 6, 9
  • 4, 8, 12, 16

and so on

how can i make this happen? ive been struggling real hard with the implementation of it, it must have sth to do with the loop but ive been trying around a week to figure this out, so all help is greatly appreciated!! critique on my already working code is also appreciated, since one of my friends said in a comment that its weird that im using 3 for loops for this issue

i tried changing things within my third for loop but couldnt quite figure that out. my other idea was creating a 2nd "int[][] result2" and have it run in its own 4th loop, but i couldnt figure out the parameters for the loop to be doing what i wanted it to do, so i scrapped it.

cannot add a foreign key constraint to a new column

I wanted to ALTER an existing table and add a new column with a foreign key constraint . I looked at Chat GPT and also some youtube videos which showed the same syntax so I used the follwoing SQL

ALTER TABLE comments ADD COLUMN Userid INT NOT NULL; ALTER TABLE comments ADD CONSTRAINT adding_fk FOREIGN KEY(Userid) REFERENCES Users(ID);

An error message is being shown when altering a table to add a column with foreign key #1452 - Cannot add or update a child row: a foreign key constraint fails (facebook.#sql-2c80_8ad, CONSTRAINT adding_fk FOREIGN KEY (Userid) REFERENCES users (ID)).

Why isn't it working?

Parameter pack and perfect forwarding

I just wrote following simple code but it doesnt compile:

#include <iostream>
#include <string>


class Obj{
public:
    std::string name = "Name";
    std::string l_name = "LastName";
    
    template<typename P>
    Obj(P&& param): name{std::forward<P>(param)} { }
    
    friend std::ostream& operator<<(std::ostream& os, const Obj& obj);
};

std::ostream& operator<<(std::ostream& os, const Obj& obj) {
    os << obj.name << ":" << obj.l_name;
    return os;
}


void print() {
    std::cout << "}";
}

template<typename T, typename ...Args>
void print(T param, Args... args) {
    std::size_t count = sizeof...(args);
    std::cout << param;
    if ( count != 0 ) {
        std::cout << ",";
    }
    print(args...);
}

template<typename... Args>
void run(Args... args) {
    std::cout << "{";
    print(args...);
}

int main() {
    Obj obj{"obj"};
    run("1", "2", 1.3, std::string{"Some Message"}, obj);
    
    return 0;
}

I just used simple parameter pack and perfect forwarding example but gives following error:

main.cpp: In instantiation of ‘Obj::Obj(P&&) [with P = Obj&]’:
main.cpp:49:8:   required from here
main.cpp:12:21: error: no matching function for call to ‘std::__cxx11::basic_string::basic_string()’
   12 |     Obj(P&& param): name{std::forward<P>(param)} {
...

If i dont use the obj paramater in the run function, the example works as expected.

How do you format the text displayed by geom_text_contour?

MWE:

library(metR)

heat_palette = c("darkred", "red", "yellow", "#00A600", "darkgreen")

heatmap_of_percentage <- function(percent) {
  # display <- sprintf("%2f%%", {{percent}})  
  # ^^ If I uncomment this, I get a bug
  c(
    geom_raster(aes(fill = {{percent}})),
    geom_contour(aes(z = {{percent}}), color = "black"),
    geom_text_contour(aes(z = {{percent}}), color = "black", stroke = 0.2),
    scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
  )
}
  
df <- expand.grid(x = 1:100, y = 1:100)
df$Z <- df$x * df$y / 100

ggplot(df, aes(x = x, y = y)) + 
  heatmap_of_percentage(percent = Z)

produces

enter image description here

I would like to modify this so that the contours are labelled 10%, 30%, etc.. How can I do this, only modifying heatmap_of_percentage (i.e. not adding an extra column in the calling code)?

I'm trying to test a specific validation case with chai, mocha and sinon, but i get an error: TypeError: expect(...).to.be.true is not a function

Issue Testing Validation Scenario in Controller Layer

I'm encountering an error while testing a validation scenario in my controller layer. The scenario involves checking for the absence of a 'name' field in the request body. Here's the test code:

it('Testing a case of absent name on req body', async function () {
    const req = { body: {} };
    const res = {
      status: sinon.stub().returnsThis(),
      json: sinon.spy(),
    };

    await productsController.insertProduct(req, res);

    expect(res.status.calledWith(400)).to.be.true();
    expect(res.json.calledWith({ message: '"name" is required' })).to.be.true();
});

The controller logic being tested is as follows:

if (!name) {
    return res.status(400).json({ 
      message: '"name" is required', 
    });
}

However, upon running the test, I encounter the error:

TypeError: expect(...).to.be.true is not a function
at Context.<anonymous> (tests/unit/controllers/products.controller.test.js:41:50)

How can I resolve this error and ensure my test for the absence of the 'name' field functions correctly?


How to execute a script after the component load in Lit-Element

I'm trying to add a prefix to the phone number input after the component load, but I'm getting an error. In a normal web component, the connectedCallback() method would be enough but here it doesn't seem to work. How can I fix this?

The error I'm getting: Uncaught TypeError: Cannot read properties of null (reading 'getAttribute')

import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js";
import "https://unpkg.com/[email protected]/build/js/intlTelInput.min.js";
import { formattedArray } from "./countries.js";

export class Form extends LitElement {
  static properties = {
    name: {},
    modalContent: {},
  };

  constructor() {
    super();
    this.countries = formattedArray;
  }

  render() {
    return html`
      <form class="flex flex-col gap-3" @submit=${this.handleSubmit}>
        <input type="text" class="form-control" placeholder="First name" name="first_name" />
        <input type="text" class="form-control" placeholder="Last name" name="last_name" />
        <input type="text" class="form-control" placeholder="Address" name="address" />
        <input type="text" class="form-control" placeholder="Zip Code" name="zip" />
        <input type="text" class="form-control" placeholder="City" name="city" />
        <select class="form-control" name="country">
          ${this.countries.map(country => html`<option value="${country}">${country}</option>`)}
        </select>
        <input type="tel" class="form-control" placeholder="Phone" name="phone" id="phone" />
        <input type="email" class="form-control" placeholder="Email" name="email" />
        <button type="submit" class="btn btn-primary">
          Continue
        </button>
      </form>
    `;
  }

  connectedCallback() {
    super.connectedCallback();
    // Initialize intlTelInput
    const input = document.querySelector("#phone");
    window.intlTelInput(input, {
      initialCountry: "auto",
      separateDialCode: true,
      utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", // Add the correct path to utils.js
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.target);
    const formObject = Object.fromEntries(formData.entries());

    // Do something with the form data, for example, log it
    console.log("Form data:", formObject);

    this.dispatchEvent(new Event('submitted', {bubbles: true, composed: true}));
  }

  createRenderRoot() {
    return this;
  }
}

customElements.define("custom-form", Form);

How to make sure browser get the rewritten SSL proxyied page ? (SSL termination, nginx)

I am trying to setup SSL termination to an apache webserver running several virtualhosts, through nginx. Here is the configuration I have so far (for one of the virtual servers):

     server {
            server_name www.example.com example.com;
            listen 80;
            return 301 https://$server_name$request_uri;
            }

     server {

               server_name www.example.com example.com;

               location / {
                        add_header       Front-End-Https    on;
                        add_header       Cache-Control "public, must-revalidate";
                        proxy_pass       http://www.example.com;
                        proxy_buffering  off;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_set_header X-Forwarded-Host $server_name;
                        proxy_redirect   http://www.example.com https://example.com;
                }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /usr/local/etc/letsencrypt/live/www.example/fullchain.pem; # managed by Certbot
    ssl_certificate_key /usr/local/etc/letsencrypt/live/www.example/privkey.pem; # managed by Certbot
    include /usr/local/etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /usr/local/etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    sub_filter_types *;
    sub_filter_once off;
    sub_filter_last_modified on;
    sub_filter "http://www.example.com" "https://www.example.com";
    }


Note, that the public DNS resolves the example.com ip to my public ip, but from the inside of my network (where proxy and webservers reside) my DNS server resolves those names to the servers private LAN addresses.

This actually works when I fetch any page or file with wget: when I use the http url, it gets 301 redirected and fetches the resources over https. I can see the resulting html pages have all http links to www.example.com or example.com, rewritten to https. If I comment/uncomment the sub_filter lines, I can observe how html gets rewritten or not, so I know this works.

Also, if I fetch anything with a browser (tested chrome, safary, firefox), it gets redirected over https and is successful.

What does NOT work: any html page fetched by a browser is NOT rewritten (when I look at "show page source" I can see all the original links with http. Not https.

This makes no sense to me, it's as if nginx decides to not rewrite html when a browser fetches a page.

I even tried to specify a user agent with wget to spoof various browsers. No problem, page gets rewritten. But fetching a page with an actual browser gets a non-rewritten html.

Obviously this causes the site to not work because browsers refuse to load some resources from http when the main page has been loaded over https.

What am I doing wrong here, how do the browsers get the non-rewritten html ?

Problema using a style.css for my website theme

I'm creating my website in on Wordpress.com and I'm implementing my theme.

I created a folder in wp-content/themes/mytheme and in this folder I created an index.php and a style.css.

Basically my style.css doesn't want to apply to my page. Here is my CSS and PHP code

index.php:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <title><?php bloginfo( 'name' ); ?></title>
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>
    <div id="content">
        <h1>Hello there!</h1>
        <p>This is my website</p>
    </div>
    <?php wp_footer(); ?>
</body>
</html>

style.css:

body {
  background-image: url('wp-content/themes/miotema/images/prima.jpg') !important;
  min-height: 100vh !important;
  background-color: rgba(234,234,234,0.5);
  background-attachment: scroll !important;
  background-repeat: no-repeat !important;
  background-size: cover;
  padding-top: 100px;
  padding-bottom: 100px;
}

I tried to put all in my php code adding the line:

style="background-image: url('wp-content/themes/miotema/images/prima.jpg') !important; background-size: cover !important; background-position: center !important;">

and in this case the style that I put in phh applies succesfully.

Is there a problem in linking the CSS to the PHP file? Is this a problem of Wordpress that has priority on my style.css?

The Flextail Tiny Bike Pump is a solid pump half the time

The tiny Flextail pump inflated this city bike tire in 45 seconds. | Photo by Thomas Ricker / The Verge

Social media’s algorithms know that I ride a bike almost every day. My quiver includes a city bike, mountain bike, and gravel bike, in addition to one or two e-bikes I’m always in the process of reviewing. I’m also the family mechanic, which makes me responsible for no less than 16 to 18 tires that I must keep inflated. So, you’d better believe I took notice when Instagram served me several ads for the Flextail Tiny Bike Bump.

The mini rechargeable pump works with Presta (the thin one) or Schrader (the old fatty) valves and promises ultra-fast inflation that maxes out at 100psi (about 7 bars) — enough for any bike that doesn’t require a stretchy wardrobe coordinated with your shoes and helmet.

The origins of the pump are suspect, as I see what looks to be the exact same product sold with branding like Cyclami, Toptoper, Rrskit, and Epoom at a variety of price points, some as low as $25. Flextail sells its version for $85 and lists the manufacturer as Huzhou Jingwei Outdoor Products on the box and device itself. The first pump Flextail sent me couldn’t pump a tire beyond 19psi before dying. Flextail sent me another that (mostly) lives up to the claims.

The thing that’s not mentioned in the ads I’ve seen is how loud the tiny pump is: 76dB at arm’s length, in my testing, which is akin to bending over to inspect a running vacuum cleaner or garbage disposal. Using it while stopped alongside forest trails generates more scowls than seeing a mountain biker in Lycra.

The Flextail Tiny Bike Pump does work, though. It’s much faster and smaller than the mini hand pumps riders usually carry in case of trouble. At 3.9 ounces (111 grams), it’s also just a bit heavier than the trusty 3.4-ounce (96 grams) Unich pump I regularly carry. But the Flextail pump also doesn’t strain your air valve mounts as much because it doesn’t require long periods of vigorously erratic pumping.

The Flextail pump’s biggest disadvantage is that it’s only good for a few zero-to-full inflations before needing a recharge, but that will vary by tire size and desired pressure. It’ll last much longer if you’re just topping up tires. Its tiny 2.59Wh battery recharges in as little as 25 minutes.

In my testing, on a city bike fitted with wide 700 x 40c tires and Schrader valve, I was able to pump one tire up to 45psi in 45 seconds. Then, moving to a gravel bike fitted with wider 700 x 42c tires and Presta valves, I was able to hit 50psi in 90 seconds before the pump quit in need of a recharge. That’s two real-world inflations per charge, for those keeping score.

The Flextail Tiny Bike Pump is so small and lightweight that I initially thought it would be ideal for bikepacking trips or even long day rides. But with only two inflations in the tank, I’d still want to carry a hand pump as backup alongside my patch kit and spare inner tube(s). But there’s no way my gram-obsessed brain would allow me to carry two pumps.

If your rig is an e-bike with a built-in USB charging port, then you’re already traveling with a giant power bank on wheels. That makes it easy to recharge the Flextail pump after depleting it because your side-of-the-road flat tire repair didn’t go as planned (it happens!). Just don’t forget your USB-C cable... and maybe a carbohydrate bar to snack on while you wait.

If you’re still interested, all I can say is that one of the two Flextail Tiny Bike Pumps I tested worked as advertised, and I bet you’ll have similar success from other brands that sell what looks to be the same Huzhou Jingwei Outdoor Products battery-powered pump for much less.

For everyone else, just buy a mini hand pump for much less money. They never need charging, are too big to lose, and will likely last a human lifetime — or two.

All photography by Thomas Ricker / The Verge

❌
❌