问:
AttributeError: 'NoneType' object has no attribute 'summary' while using tradingview_ta library
I am getting AttributeError: 'NoneType' object has no attribute 'summary' after some displaying some output of my code.

```<code>import pandas as pd
from tradingview_ta import TA_Handler, Interval, Exchange

stkfilename = f"F:/Python/HistoricStockInfo/StockName.csv"
stkFile = pd.read_csv(stkfilename)
for i in range(len(stkFile)):
    #print(stkFile['Symbol'].iloc[i])
    NIFTY = TA_Handler(
    symbol=stkFile['Symbol'].iloc[i],
    #symbol = "ACE",
    screener="india",
    exchange="NSE",
    interval=Interval.INTERVAL_1_WEEK
    )

    result = NIFTY.get_analysis().summary
    if NIFTY.get_analysis().summary:
        summary = (result.find('summary').text or '').encode('utf8')

    #if result['RECOMMENDATION']=="STRONG_BUY":
    if result is None:
        print(stkFile['Symbol'].iloc[i])
        print(result)
    else:
        print("Symbol not found")
</code>```

Here is my code.

What I am trying to do it to read Stock Symbols from my excel file and pass it to TA_handler function to get result using get_analysis method. Trying to print the results of symbols found on trading view as per criteria.

Giving me below error after some output.

```<code>5PAISA
{'RECOMMENDATION': 'SELL', 'BUY': 6, 'SELL': 10, 'NEUTRAL': 10}
63MOONS
{'RECOMMENDATION': 'SELL', 'BUY': 3, 'SELL': 14, 'NEUTRAL': 9}
A2ZINFRA
  File "f:\Python\datacheck.py", line 27, in <module>
    result = NIFTY.get_analysis().summary
AttributeError: 'NoneType' object has no attribute 'summary'
</code>```

What I am trying to do it to read Stock Symbols from my excel file and pass it to TA_handler function to get result using get_analysis method. Trying to print the results of symbols found on trading view as per criteria.

SymbolName.csv looks like below..

enter image description here

Body:
I am getting AttributeError: 'NoneType' object has no attribute 'summary' after some displaying some output of my code.

import pandas as pd
from tradingview_ta import TA_Handler, Interval, Exchange

stkfilename = f"F:/Python/HistoricStockInfo/StockName.csv"
stkFile = pd.read_csv(stkfilename)
for i in range(len(stkFile)):
    #print(stkFile['Symbol'].iloc[i])
    NIFTY = TA_Handler(
    symbol=stkFile['Symbol'].iloc[i],
    #symbol = "ACE",
    screener="india",
    exchange="NSE",
    interval=Interval.INTERVAL_1_WEEK
    )

    result = NIFTY.get_analysis().summary
    if NIFTY.get_analysis().summary:
        summary = (result.find('summary').text or '').encode('utf8')

    #if result['RECOMMENDATION']=="STRONG_BUY":
    if result is None:
        print(stkFile['Symbol'].iloc[i])
        print(result)
    else:
        print("Symbol not found")

Here is my code.

What I am trying to do it to read Stock Symbols from my excel file and pass it to TA_handler function to get result using get_analysis method. Trying to print the results of symbols found on trading view as per criteria.

Giving me below error after some output.

5PAISA
{'RECOMMENDATION': 'SELL', 'BUY': 6, 'SELL': 10, 'NEUTRAL': 10}
63MOONS
{'RECOMMENDATION': 'SELL', 'BUY': 3, 'SELL': 14, 'NEUTRAL': 9}
A2ZINFRA
  File "f:\Python\datacheck.py", line 27, in <module>
    result = NIFTY.get_analysis().summary
AttributeError: 'NoneType' object has no attribute 'summary'

What I am trying to do it to read Stock Symbols from my excel file and pass it to TA_handler function to get result using get_analysis method. Trying to print the results of symbols found on trading view as per criteria.

SymbolName.csv looks like below..

enter image description here


来源: stackexchange

问:
Why does my model predict the same label?
I am training a graph convolution neural network to classify EEG signals into emotion classes. The input of my data is an array of size [12803216]-->[number of subjects * numbers of channels (nodes) * features of each node]. The output should be class 0(Negative) or class 1(Positive).The data is slightly imbalanced (45% class 0 and 55% class 1). The problem is that my model always predict label 0 as output for all inputs in the training stage regardless of the convolution function.

What is wrong with my code and how can I fix it? Any comments are welcome.

connectivity at the below code is predefined  based at the connections of the 32 electrodes(nodes)

```<code>import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, SAGEConv, ResGatedGraphConv, global_mean_pool, BatchNorm
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, f1_score, accuracy_score
</code>```
```<code>labels = np.load("/content/drive/MyDrive/ValenceLabels_thres_5.npy")
labels = np.array(labels, dtype='int64')
labels.shape
</code>```
```<code>class EEGraph(nn.Module):

  def __init__(self, embedding_dim, first_conv, n_layers, conv_layer):
    super(EEGraph, self).__init__()
    self.n_layers = n_layers

    self.convs = []
    self.bns = []
    d_in = embedding_dim
    d_out = first_conv
    for i in range(n_layers):
      self.convs.append(conv_layer(d_in, d_out))
      self.bns.append(BatchNorm(d_out, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True))

      if i < n_layers - 1:
        d_in, d_out = d_out, 2*d_out

    self.convs = torch.nn.ModuleList(self.convs)
    self.bns = torch.nn.ModuleList(self.bns)
    self.project = nn.Linear(d_out, 3) # d_in beacu

    self.project.apply(lambda x: nn.init.xavier_normal_(x.weight, gain=1) if type(x) == nn.Linear else None)

  def forward(self, x, edge_index):
    for i, (conv, bn) in enumerate(zip(self.convs, self.bns)):
      x = conv(x, edge_index).permute(0, 2, 1)
      x = bn(x)
      x = F.dropout(F.leaky_relu(x, negative_slope=0.01), p=0.5, training=self.training).permute(0, 2, 1)
    out = x.mean(dim=1).squeeze(dim=-1)
    out = self.project(out)
    return F.softmax(out, dim=-1)
</code>```
```<code>device = torch.device("cuda")
</code>```
```<code>connectivity = [[channel_order.index(e[0]), channel_order.index(e[1])] for e in edges]
connectivity = torch.tensor(connectivity).t().contiguous().to(device)
</code>```
```<code>best_f1_score = -1
best_trial_name = None
n_epochs = 500
lr = 1e-3
weight_decay = 1e-5
batch_size = 63
criterion = nn.CrossEntropyLoss()
for node_dim in [16]:
  node_features = np.load(f"/content/deap_graph_valence{node_dim}_1.npy")
  A, Xte, yA, yte = train_test_split(node_features, labels, test_size=0.2, shuffle=True, stratify=labels, random_state=0)
  Xtr, Xtr_valid, ytr, ytr_valid = train_test_split(A, yA, test_size=0.2, shuffle=True, stratify=yA, random_state=0)
  Xtr = torch.tensor(Xtr).float().to(device)
  Xtr_valid = torch.tensor(Xtr_valid).float().to(device)
  Xte = torch.tensor(Xte).float().to(device)
  ytr = torch.tensor(ytr).to(device)
  #ytr_valid = torch.tensor(ytr_valid).to(device)
  #yte = torch.tensor(yte).to(device)
  for conv_fn in [GCNConv, SAGEConv, ResGatedGraphConv]:
    for n_layers in range(1, 4):
      for conv_dim in [32, 64, 128,256]:
        trial_name = f"node_dim_{node_dim}-conv_fn_{conv_fn.__name__}-conv_layers_{n_layers}-conv_dim_{conv_dim}"
        print(f"@: {trial_name}")
        model = EEGraph(embedding_dim=Xtr.shape[-1],
                        first_conv=conv_dim,
                        n_layers=n_layers,
                        conv_layer=conv_fn).to(device)

        optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
        for epoch in range(n_epochs):
          model.train()
          indices = torch.randperm(len(Xtr))
          for j, batch in enumerate(indices.view(-1, 63)):
            optimizer.zero_grad()

            batch_input = Xtr[batch]
            outputs = model(batch_input, connectivity)
            loss = criterion(outputs, ytr[batch])
            loss.backward()
            optimizer.step()

        with torch.no_grad():
          model.eval()
          outputs = model(Xtr_valid, connectivity)
          output_classes = torch.argmax(outputs, dim=-1).cpu().numpy()
          f1 = f1_score(ytr_valid, output_classes, average="macro")
          if f1 > best_f1_score:
            best_trial_name = trial_name
            best_f1_score = f1
            print("-"*100)
            print(f"Best model so far: {best_trial_name}")
            print(f"Best F1 Score: %{100*best_f1_score:.2f}")
            test_outputs = model(Xte, connectivity)
            test_output_classes = torch.argmax(test_outputs, dim=-1).cpu().numpy()
            print(classification_report(yte, test_output_classes, target_names=["Negative", "Positive"]))
            print("-"*100)
            print()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am training a graph convolution neural network to classify EEG signals into emotion classes. The input of my data is an array of size [12803216]-->[number of subjects * numbers of channels (nodes) * features of each node]. The output should be class 0(Negative) or class 1(Positive).The data is slightly imbalanced (45% class 0 and 55% class 1). The problem is that my model always predict label 0 as output for all inputs in the training stage regardless of the convolution function.

What is wrong with my code and how can I fix it? Any comments are welcome.

connectivity at the below code is predefined  based at the connections of the 32 electrodes(nodes)

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, SAGEConv, ResGatedGraphConv, global_mean_pool, BatchNorm
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, f1_score, accuracy_score

labels = np.load("/content/drive/MyDrive/ValenceLabels_thres_5.npy")
labels = np.array(labels, dtype='int64')
labels.shape

class EEGraph(nn.Module):

  def __init__(self, embedding_dim, first_conv, n_layers, conv_layer):
    super(EEGraph, self).__init__()
    self.n_layers = n_layers

    self.convs = []
    self.bns = []
    d_in = embedding_dim
    d_out = first_conv
    for i in range(n_layers):
      self.convs.append(conv_layer(d_in, d_out))
      self.bns.append(BatchNorm(d_out, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True))

      if i < n_layers - 1:
        d_in, d_out = d_out, 2*d_out

    self.convs = torch.nn.ModuleList(self.convs)
    self.bns = torch.nn.ModuleList(self.bns)
    self.project = nn.Linear(d_out, 3) # d_in beacu

    self.project.apply(lambda x: nn.init.xavier_normal_(x.weight, gain=1) if type(x) == nn.Linear else None)

  def forward(self, x, edge_index):
    for i, (conv, bn) in enumerate(zip(self.convs, self.bns)):
      x = conv(x, edge_index).permute(0, 2, 1)
      x = bn(x)
      x = F.dropout(F.leaky_relu(x, negative_slope=0.01), p=0.5, training=self.training).permute(0, 2, 1)
    out = x.mean(dim=1).squeeze(dim=-1)
    out = self.project(out)
    return F.softmax(out, dim=-1)

device = torch.device("cuda")

connectivity = [[channel_order.index(e[0]), channel_order.index(e[1])] for e in edges]
connectivity = torch.tensor(connectivity).t().contiguous().to(device)

best_f1_score = -1
best_trial_name = None
n_epochs = 500
lr = 1e-3
weight_decay = 1e-5
batch_size = 63
criterion = nn.CrossEntropyLoss()
for node_dim in [16]:
  node_features = np.load(f"/content/deap_graph_valence{node_dim}_1.npy")
  A, Xte, yA, yte = train_test_split(node_features, labels, test_size=0.2, shuffle=True, stratify=labels, random_state=0)
  Xtr, Xtr_valid, ytr, ytr_valid = train_test_split(A, yA, test_size=0.2, shuffle=True, stratify=yA, random_state=0)
  Xtr = torch.tensor(Xtr).float().to(device)
  Xtr_valid = torch.tensor(Xtr_valid).float().to(device)
  Xte = torch.tensor(Xte).float().to(device)
  ytr = torch.tensor(ytr).to(device)
  #ytr_valid = torch.tensor(ytr_valid).to(device)
  #yte = torch.tensor(yte).to(device)
  for conv_fn in [GCNConv, SAGEConv, ResGatedGraphConv]:
    for n_layers in range(1, 4):
      for conv_dim in [32, 64, 128,256]:
        trial_name = f"node_dim_{node_dim}-conv_fn_{conv_fn.__name__}-conv_layers_{n_layers}-conv_dim_{conv_dim}"
        print(f"@: {trial_name}")
        model = EEGraph(embedding_dim=Xtr.shape[-1],
                        first_conv=conv_dim,
                        n_layers=n_layers,
                        conv_layer=conv_fn).to(device)

        optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
        for epoch in range(n_epochs):
          model.train()
          indices = torch.randperm(len(Xtr))
          for j, batch in enumerate(indices.view(-1, 63)):
            optimizer.zero_grad()

            batch_input = Xtr[batch]
            outputs = model(batch_input, connectivity)
            loss = criterion(outputs, ytr[batch])
            loss.backward()
            optimizer.step()

        with torch.no_grad():
          model.eval()
          outputs = model(Xtr_valid, connectivity)
          output_classes = torch.argmax(outputs, dim=-1).cpu().numpy()
          f1 = f1_score(ytr_valid, output_classes, average="macro")
          if f1 > best_f1_score:
            best_trial_name = trial_name
            best_f1_score = f1
            print("-"*100)
            print(f"Best model so far: {best_trial_name}")
            print(f"Best F1 Score: %{100*best_f1_score:.2f}")
            test_outputs = model(Xte, connectivity)
            test_output_classes = torch.argmax(test_outputs, dim=-1).cpu().numpy()
            print(classification_report(yte, test_output_classes, target_names=["Negative", "Positive"]))
            print("-"*100)
            print()


问:
How can i pass prop to sass keyframe percent from jsx
Hi in my react project i need to create dynamic keyframes. I need to pass percent variable's value from jsx code. How can i do it? My SCSS Code :

```<code>:root {
    --percent: 95%;
    --dim: 0.75;
--period: 1s;
--delay: 1s;
}

$percent: 95%;
$dim: var(--dim);
$period: var(--period);
$delay: var(--delay);

@mixin animation($percent,$dim, $period, $delay) {
    @keyframes blink {
        #{$percent} {
            opacity: 0
        }
        100% {
            opacity: $dim
        }
    }

    animation: blink $period infinite $delay ;
}

.MarkerWithId{
    @include animation($percent, $dim, $period, $delay)
}
</code>```

I tried to change the percent with JavaScript after page render but it didnt make any change.And I cant use var(--percent) for $percent

Body:
Hi in my react project i need to create dynamic keyframes. I need to pass percent variable's value from jsx code. How can i do it? My SCSS Code :

:root {
    --percent: 95%;
    --dim: 0.75;
--period: 1s;
--delay: 1s;
}

$percent: 95%;
$dim: var(--dim);
$period: var(--period);
$delay: var(--delay);

@mixin animation($percent,$dim, $period, $delay) {
    @keyframes blink {
        #{$percent} {
            opacity: 0
        }
        100% {
            opacity: $dim
        }
    }

    animation: blink $period infinite $delay ;
}

.MarkerWithId{
    @include animation($percent, $dim, $period, $delay)
}

I tried to change the percent with JavaScript after page render but it didnt make any change.And I cant use var(--percent) for $percent


问:
window.addEventListener("scroll") is not Firing in Nextjs project
In my case I need a some way to detect  scrollY changes dectection. But bellow code is not working at all!

```<code>useEffect(() => {
    window.addEventListener("scroll", () => {
      console.log("scroll");
    });
  }, []);
</code>```

Why and How can I fix It?

Edit:

```<code>import "../styles/globals.css";
import type { AppProps } from "next/app";
import { LangContextProvider } from "../context/language";
import React, { useState, useEffect, useCallback } from "react";
import MultiLang from "../components/MultiLang";
import useScroll from "../components/Scroll";

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    window.addEventListener("scroll", () => {
      console.log("data");
    });
  }, []);
  return (
    <LangContextProvider>
      <MultiLang>
        <Component {...pageProps} />
      </MultiLang>
    </LangContextProvider>
  );
}

export default MyApp;
</code>```

Body:
In my case I need a some way to detect  scrollY changes dectection. But bellow code is not working at all!

useEffect(() => {
    window.addEventListener("scroll", () => {
      console.log("scroll");
    });
  }, []);

Why and How can I fix It?

Edit:

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { LangContextProvider } from "../context/language";
import React, { useState, useEffect, useCallback } from "react";
import MultiLang from "../components/MultiLang";
import useScroll from "../components/Scroll";

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    window.addEventListener("scroll", () => {
      console.log("data");
    });
  }, []);
  return (
    <LangContextProvider>
      <MultiLang>
        <Component {...pageProps} />
      </MultiLang>
    </LangContextProvider>
  );
}

export default MyApp;


问:
Storing an array of references to variables
I've a set of html select tags I've used PHP to render. :

```<code>$templates = array( 'Template1', 'Template2', 'Template3', 'Template4');
$templates_dropdown =  '<select required id="templates" name="admin[template_select]">
    <option value="">'.__( 'Pick a template', 'textdomain' ).'</option>';
foreach( $templates as $value){
    $template_value = esc_html( $value );
    $templates_dropdown .= '<option value="' . $template_value . '">' . $template_value . '</option>' . "\n";
}
$templates_dropdown .= '</select>';
</code>```

There are about 5 select tags which I've to close every time like the last line above. Instead of closing each one, is there a way to alter the original variable using variable reference like:

```<code>$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
</code>```

Something along the lines of:

```<code> //this doesnt work
    $test = 'world one';
    $test2 = 'world two';
    $test3 = 'world three';
    $close_select_tags = array( &$test, &$test2, &$test3);
    foreach($close_select_tags as $value){
      $value .= 'check';
    }
    echo $test;
    echo "\n";
    echo $test2;
    echo "\n";
    echo $test3;
    echo "\n";
</code>```

I know I can simply use array destructuring or store the select tag variables inside an array, just wondering why storing the references in an array and altering the values doesn't work.

Body:
I've a set of html select tags I've used PHP to render. :

$templates = array( 'Template1', 'Template2', 'Template3', 'Template4');
$templates_dropdown =  '<select required id="templates" name="admin[template_select]">
    <option value="">'.__( 'Pick a template', 'textdomain' ).'</option>';
foreach( $templates as $value){
    $template_value = esc_html( $value );
    $templates_dropdown .= '<option value="' . $template_value . '">' . $template_value . '</option>' . "\n";
}
$templates_dropdown .= '</select>';

There are about 5 select tags which I've to close every time like the last line above. Instead of closing each one, is there a way to alter the original variable using variable reference like:

$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.

Something along the lines of:

 //this doesnt work
    $test = 'world one';
    $test2 = 'world two';
    $test3 = 'world three';
    $close_select_tags = array( &$test, &$test2, &$test3);
    foreach($close_select_tags as $value){
      $value .= 'check';
    }
    echo $test;
    echo "\n";
    echo $test2;
    echo "\n";
    echo $test3;
    echo "\n";

I know I can simply use array destructuring or store the select tag variables inside an array, just wondering why storing the references in an array and altering the values doesn't work.


问:
sh.ErrorReturnCOde_2 error when using buildozer after adding pandas as requirement
```<code>[[INFO]:    Building liblzma for arm64-v8a
[INFO]:    -> directory context /mnt/d/seaborn/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/liblzma/arm64-v8a__ndk_target_21/liblzma
[DEBUG]:   -> running autoreconf -vif
[DEBUG]:        autoreconf: export WARNINGS=
[DEBUG]:        autoreconf: Entering directory '.'
[DEBUG]:        autoreconf: running: autopoint --force
[DEBUG]:        Can't exec "autopoint": No such file or directory at /usr/share/autoconf/Autom4te/FileUtils.pm line 293.
[DEBUG]:        autoreconf: error: autopoint failed with exit status: 2
Exception in thread background thread for pid 20841:
Traceback (most recent call last):
  File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.10/threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 1641, in wrap
    fn(*rgs, **kwargs)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 2569, in background_thread
    handle_exit_code(exit_code)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 2269, in fn
    return self.command.handle_command_exit_code(exit_code)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 869, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_2:
</code>```

I have set the p4b to develop mode and added all the requirements which i got from pipdeptree as you can see in buildozer.specbelow:

Body:
[[INFO]:    Building liblzma for arm64-v8a
[INFO]:    -> directory context /mnt/d/seaborn/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/liblzma/arm64-v8a__ndk_target_21/liblzma
[DEBUG]:   -> running autoreconf -vif
[DEBUG]:        autoreconf: export WARNINGS=
[DEBUG]:        autoreconf: Entering directory '.'
[DEBUG]:        autoreconf: running: autopoint --force
[DEBUG]:        Can't exec "autopoint": No such file or directory at /usr/share/autoconf/Autom4te/FileUtils.pm line 293.
[DEBUG]:        autoreconf: error: autopoint failed with exit status: 2
Exception in thread background thread for pid 20841:
Traceback (most recent call last):
  File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.10/threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 1641, in wrap
    fn(*rgs, **kwargs)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 2569, in background_thread
    handle_exit_code(exit_code)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 2269, in fn
    return self.command.handle_command_exit_code(exit_code)
  File "/home/rock/.local/lib/python3.10/site-packages/sh.py", line 869, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_2:

I have set the p4b to develop mode and added all the requirements which i got from pipdeptree as you can see in buildozer.specbelow:


问:
You must add reference to assembly even though the package is added in published Nuget
I have a build job that publishes a Nuget Package

Inside the Nuget Package I have an Appium library  but whenever I am trying to use this published Nuget I am getting this error for Appium only

Can anyone help me out on this Issue....I have been trying to figure out this whole day


问:
Faster way to calculate Hessian of two distinct groups of parameters
PyTorch offers methods to calculate the Hessian of a function (torch.autograd.functional.hessian) and to calculate a Hessian vector product for a given function (torch.autograd.functional.hvp). These methods assume the same set of parameters for the 1st and 2nd derivatives. However, I want to calculate only cross-derivatives of two distinct parameter groups 1 and 2. While the above functions can give me the Hessian H_11/H_22 (doesn't include cross-terms) or H_(12)(12) (includes derivatives I don't need), I am only interested in H_12. I am able to calculate this as follows:

import torch

''' Construct model '''
model1 = torch.nn.Sequential(torch.nn.Linear(1, 5), torch.nn.Tanh(), torch.nn.Linear(5, 1))
model2 = torch.nn.Sequential(torch.nn.Linear(1, 3), torch.nn.Tanh(), torch.nn.Linear(3, 1))

''' Calculate some (arbitrary) loss '''
x = torch.ones(1, requires_grad=True)
y = model1(x) * model2(x)
loss = (y-1)**2

''' Calculate Hessian d^2L/dx dy '''
# Calculate number of variables in each model
n_1 = sum(p.numel() for p in model1.parameters())
n_2 = sum(p.numel() for p in model2.parameters())

# Allocate Hessian size
H_12 = torch.zeros((n_1, n_2))

# Calculate Jacobian w.r.t. model 1 parameters
J_1 = torch.autograd.grad(loss, list(model1.parameters()), create_graph=True)

# Function to get the derivative of the i-th parameter of model_1
def ith_element (params, index):
    for p in params:
        if torch.numel(p) < index + 1:
            index -= torch.numel(p)
        else:
            return p.flatten()[index]

# Fill in Hessian
for i in range(n_1):
    result = torch.autograd.grad(ith_element(J_1, i), list(model2.parameters()), retain_graph=True)
    H_12[i] = torch.cat([r.flatten() for r in result])

print(H_12)
```

However, this is extremely slow because it calls autograd.grad for every parameter of model1. This is fine for these small example models, but not for my models with 10000+ parameters. Is there any way to speed this up?

Body:
PyTorch offers methods to calculate the Hessian of a function (torch.autograd.functional.hessian) and to calculate a Hessian vector product for a given function (torch.autograd.functional.hvp). These methods assume the same set of parameters for the 1st and 2nd derivatives. However, I want to calculate only cross-derivatives of two distinct parameter groups 1 and 2. While the above functions can give me the Hessian H_11/H_22 (doesn't include cross-terms) or H_(12)(12) (includes derivatives I don't need), I am only interested in H_12. I am able to calculate this as follows:

import torch

''' Construct model '''
model1 = torch.nn.Sequential(torch.nn.Linear(1, 5), torch.nn.Tanh(), torch.nn.Linear(5, 1))
model2 = torch.nn.Sequential(torch.nn.Linear(1, 3), torch.nn.Tanh(), torch.nn.Linear(3, 1))

''' Calculate some (arbitrary) loss '''
x = torch.ones(1, requires_grad=True)
y = model1(x) * model2(x)
loss = (y-1)**2

''' Calculate Hessian d^2L/dx dy '''
# Calculate number of variables in each model
n_1 = sum(p.numel() for p in model1.parameters())
n_2 = sum(p.numel() for p in model2.parameters())

# Allocate Hessian size
H_12 = torch.zeros((n_1, n_2))

# Calculate Jacobian w.r.t. model 1 parameters
J_1 = torch.autograd.grad(loss, list(model1.parameters()), create_graph=True)

# Function to get the derivative of the i-th parameter of model_1
def ith_element (params, index):
    for p in params:
        if torch.numel(p) < index + 1:
            index -= torch.numel(p)
        else:
            return p.flatten()[index]

# Fill in Hessian
for i in range(n_1):
    result = torch.autograd.grad(ith_element(J_1, i), list(model2.parameters()), retain_graph=True)
    H_12[i] = torch.cat([r.flatten() for r in result])

print(H_12)

However, this is extremely slow because it calls autograd.grad for every parameter of model1. This is fine for these small example models, but not for my models with 10000+ parameters. Is there any way to speed this up?


问:
How to set cloud_rolename in Azure Monitor Metrics using python
When I am logging traces, I can easily set the cloud_rolename.

https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-map?tabs=python#set-or-override-cloud-role-name

But when logging metrics, I can't find a way. Docs doesn't say anything

https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-map?tabs=python#set-or-override-cloud-role-name

Is it possible?


问:
How to add font-face in storybook in nx app?
My app is built using React and NX. I am trying to add @font-face in storybook using preview-head.html file.

This is my font-face.

```<code>@font-face {
  font-family: 'Switzer-Regular';
  src: url('../assets/fonts/Switzer-Regular.woff2') format('woff2'),
    url('../assets/fonts/Switzer-Regular.woff') format('woff'),
    url('../assets/fonts/Switzer-Regular.ttf') format('truetype');
  font-weight: 400;
  font-display: swap;
  font-style: normal;
}
</code>```

This is my preview-head.html

```<code><style>
  * {
    font-family: 'Switzer-Regular';
    src: url('fonts/Switzer-Regular.woff2') format('woff2'),
      url('fonts/Switzer-Regular.woff') format('woff'),
      url('fonts/Switzer-Regular.ttf') format('truetype');
    font-weight: 400;
    font-display: swap;
    font-style: normal;
  }
</style>
</code>```

After running this code snippet my storybook was able to capture the font-family, font-weight, font-style But src and font-display says it is unknown property name.

I tried exploring NX storybook docs. But could not find any working solution. Any help would be appreciated !

Screenshot from dev tools(elements):

Body:
My app is built using React and NX. I am trying to add @font-face in storybook using preview-head.html file.

This is my font-face.

@font-face {
  font-family: 'Switzer-Regular';
  src: url('../assets/fonts/Switzer-Regular.woff2') format('woff2'),
    url('../assets/fonts/Switzer-Regular.woff') format('woff'),
    url('../assets/fonts/Switzer-Regular.ttf') format('truetype');
  font-weight: 400;
  font-display: swap;
  font-style: normal;
}

This is my preview-head.html

After running this code snippet my storybook was able to capture the font-family, font-weight, font-style But src and font-display says it is unknown property name.

I tried exploring NX storybook docs. But could not find any working solution. Any help would be appreciated !

Screenshot from dev tools(elements):


问:
Removing gravity component from android accelerometer
I am collecting acceleromter data using android's phone TYPE_ACCELEROMETER sensor. My problem is I want to remove the gravity component from these readings so that data makes sense. I have found many solutions for this problem but can't decide which one actually works. Is subtracting gravity value obtained from TYPE_GRAVITY from acceleromter readings does the job?


问:
How to import all photos from gallery in android?
I am creating an app in which right now the user has to select some photos from their gallery with the onClick function of a button using intent.

```<code>Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
</code>```

Is there a way to get all the images in the user's gallery with just the press of the button?

Body:
I am creating an app in which right now the user has to select some photos from their gallery with the onClick function of a button using intent.

Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

Is there a way to get all the images in the user's gallery with just the press of the button?


问:
How to build a C++ non-PIC shared library that links to a static library
My aim is to provide a new C++ shared library that will by called by Python using Pybind, to expose existing C++ functionality.  The Python aspect is not super relevant here, but just for context.

The shared library essentially provides an interface, that then calls functionality in an existing project, called "core", provided by a static library (libcore.a).  Core is NOT built with PIC.

For now, I am simply trying to get the basics working:

test_app - this is a C++ stand in for the Python client - the problem I will get to is demonstrated here

lib_interface - the .so I want to generate

lib_core - the .a representing all the existing functionality

It is important to me NOT to use PIC, but instead relocation
(https://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries/).

This is all with CMAKE, on Ubuntu 20, gcc 9.4.0.

\CmakeLists.txt

```<code>cmake_minimum_required(VERSION 3.15)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-pthread -Wall -fopenmp -fuse-ld=lld")
project("test LANGUAGES CXX")

add_subdirectory(test_app)
add_subdirectory(lib_interface)
add_subdirectory(lib_core)

</code>```

test_app\CmakeLists.txt

```<code>add_executable(test_app main.cpp)

target_link_libraries(test_app PUBLIC
        ${CMAKE_BINARY_DIR}/lib_interface/liblib_interface.so
        )

</code>```

test_app\main.cpp

```<code>#include <iostream>
#include "../lib_interface/lib_interface.h"

int main()
{
    std::cout << "Test app start" << std::endl;
    lib_interface::foo();
    return 0;
}
</code>```

lib_interface\CmakeLists.txt

```<code>
add_library(lib_interface SHARED lib_interface.cpp)

set(CMAKE_SHARED_LIBRARY_CXX_FLAGS "") # in order to remove -fPIC

target_link_libraries(lib_interface PRIVATE
        ${CMAKE_BINARY_DIR}/lib_core/liblib_core.a
        )

</code>```

lib_interface\lib_interface.cpp

```<code>#include <iostream>
#include "lib_interface.h"
#include "../lib_core/lib_core.h"

void lib_interface::foo()
{
    std::cout << "lib_interface - foo"<< std::endl;

    std::cout << "calling lib_core"<< std::endl;
    lib_core::bla();
}
</code>```

lib_core\CmakeLists.txt

```<code>
add_library(lib_core STATIC lib_core.cpp)

</code>```

lib_core\lib_core.cpp

```<code>#include <iostream>
#include "lib_core.h"

void lib_core::bla()
{
    std::cout << "lib_core - bla"<< std::endl;
}

</code>```

Building as presented, I get this error

```<code>FAILED: lib_interface/liblib_interface.so
: && /usr/bin/c++ -pthread -Wall -fopenmp -fuse-ld=lld -g   -shared -Wl,-soname,liblib_interface.so -o lib_interface/liblib_interface.so lib_interface/CMakeFiles/lib_interface.dir/lib_interface.cpp.o  lib_core/liblib_core.a && :
ld.lld: error: relocation R_X86_64_PC32 cannot be used against symbol std::cout; recompile with -fPIC
</code>```

Adding -fPIC is not acceptable - this is one of those cases where the performance impact is a problem, and up-front loading time is best.

Going off of Possible to build a shared library with static link used library? , it seems that -static is needed.

Adding

```<code>set_target_properties(lib_interface PROPERTIES LINK_FLAGS "-static")
</code>```

to lib_interface\CMakeList.txt, I get:

```<code>FAILED: lib_interface/liblib_interface.so
: && /usr/bin/c++ -pthread -Wall -fopenmp -fuse-ld=lld -g  -static -shared -Wl,-soname,liblib_interface.so -o lib_interface/liblib_interface.so lib_interface/CMakeFiles/lib_interface.dir/lib_interface.cpp.o  lib_core/liblib_core.a && :
ld.lld: error: can't create dynamic relocation R_X86_64_32 against symbol: __TMC_END__ in readonly segment; recompile object files with -fPIC or pass '-Wl,-z,notext' to allow text relocations in the output
</code>```

which seems more promising.

Adding

```<code>add_executable(test_app main.cpp)

target_link_libraries(test_app PUBLIC
        ${CMAKE_BINARY_DIR}/lib_interface/liblib_interface.so
        )

</code>```0

to lib_interface\CMakeList.txt, the error is now:

```<code>add_executable(test_app main.cpp)

target_link_libraries(test_app PUBLIC
        ${CMAKE_BINARY_DIR}/lib_interface/liblib_interface.so
        )

</code>```1

Appreciate a pointer on where I'm going wrong.

Body:
My aim is to provide a new C++ shared library that will by called by Python using Pybind, to expose existing C++ functionality.  The Python aspect is not super relevant here, but just for context.

The shared library essentially provides an interface, that then calls functionality in an existing project, called "core", provided by a static library (libcore.a).  Core is NOT built with PIC.

For now, I am simply trying to get the basics working:

test_app - this is a C++ stand in for the Python client - the problem I will get to is demonstrated here

lib_interface - the .so I want to generate

lib_core - the .a representing all the existing functionality

It is important to me NOT to use PIC, but instead relocation
(https://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries/).

This is all with CMAKE, on Ubuntu 20, gcc 9.4.0.

\CmakeLists.txt

cmake_minimum_required(VERSION 3.15)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-pthread -Wall -fopenmp -fuse-ld=lld")
project("test LANGUAGES CXX")

add_subdirectory(test_app)
add_subdirectory(lib_interface)
add_subdirectory(lib_core)

test_app\CmakeLists.txt

add_executable(test_app main.cpp)

target_link_libraries(test_app PUBLIC
        ${CMAKE_BINARY_DIR}/lib_interface/liblib_interface.so
        )

test_app\main.cpp

#include <iostream>
#include "../lib_interface/lib_interface.h"

int main()
{
    std::cout << "Test app start" << std::endl;
    lib_interface::foo();
    return 0;
}

lib_interface\CmakeLists.txt

add_library(lib_interface SHARED lib_interface.cpp)

set(CMAKE_SHARED_LIBRARY_CXX_FLAGS "") # in order to remove -fPIC

target_link_libraries(lib_interface PRIVATE
        ${CMAKE_BINARY_DIR}/lib_core/liblib_core.a
        )

lib_interface\lib_interface.cpp

#include <iostream>
#include "lib_interface.h"
#include "../lib_core/lib_core.h"

void lib_interface::foo()
{
    std::cout << "lib_interface - foo"<< std::endl;

    std::cout << "calling lib_core"<< std::endl;
    lib_core::bla();
}

lib_core\CmakeLists.txt

add_library(lib_core STATIC lib_core.cpp)

lib_core\lib_core.cpp

#include <iostream>
#include "lib_core.h"

void lib_core::bla()
{
    std::cout << "lib_core - bla"<< std::endl;
}

Building as presented, I get this error

FAILED: lib_interface/liblib_interface.so
: && /usr/bin/c++ -pthread -Wall -fopenmp -fuse-ld=lld -g   -shared -Wl,-soname,liblib_interface.so -o lib_interface/liblib_interface.so lib_interface/CMakeFiles/lib_interface.dir/lib_interface.cpp.o  lib_core/liblib_core.a && :
ld.lld: error: relocation R_X86_64_PC32 cannot be used against symbol std::cout; recompile with -fPIC

Adding -fPIC is not acceptable - this is one of those cases where the performance impact is a problem, and up-front loading time is best.

Going off of Possible to build a shared library with static link used library? , it seems that -static is needed.

Adding

set_target_properties(lib_interface PROPERTIES LINK_FLAGS "-static")

to lib_interface\CMakeList.txt, I get:

FAILED: lib_interface/liblib_interface.so
: && /usr/bin/c++ -pthread -Wall -fopenmp -fuse-ld=lld -g  -static -shared -Wl,-soname,liblib_interface.so -o lib_interface/liblib_interface.so lib_interface/CMakeFiles/lib_interface.dir/lib_interface.cpp.o  lib_core/liblib_core.a && :
ld.lld: error: can't create dynamic relocation R_X86_64_32 against symbol: __TMC_END__ in readonly segment; recompile object files with -fPIC or pass '-Wl,-z,notext' to allow text relocations in the output

which seems more promising.

Adding

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,-z,notext")

to lib_interface\CMakeList.txt, the error is now:

FAILED: lib_interface/liblib_interface.so
: && /usr/bin/c++ -pthread -Wall -fopenmp -fuse-ld=lld -Wl,-z,notext -g  -static -shared -Wl,-soname,liblib_interface.so -o lib_interface/liblib_interface.so lib_interface/CMakeFiles/lib_interface.dir/lib_interface.cpp.o  lib_core/liblib_core.a && :
ld.lld: error: relocation R_X86_64_32 cannot be used against symbol __TMC_END__; recompile with -fPIC

Appreciate a pointer on where I'm going wrong.


问:
How do I call an action hook into wp_ajax hook callback function
I have to trigger an ajax call based on a custom field changes on checkout form which is to add a discount. But if I call the hook to add discount into subtotal of the cart it does not do anything. Note that ajax call is working fine.</p>
```<code>add_action('wp_ajax_test', 'test');
add_action('wp_ajax_nopriv_test', 'test');

function test(){
  add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
}

function add_custom_fees( WC_Cart $cart ){

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.2;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}
</code>```

Body:
I have to trigger an ajax call based on a custom field changes on checkout form which is to add a discount. But if I call the hook to add discount into subtotal of the cart it does not do anything. Note that ajax call is working fine.

add_action('wp_ajax_test', 'test');
add_action('wp_ajax_nopriv_test', 'test');

function test(){
  add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
}

function add_custom_fees( WC_Cart $cart ){

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.2;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}


问:
How to see all values in the user’s theme configuration
I am writing plugin to add custom styles in TailwindCSS, but I am a bit confused with values of theme(). I don't know how to see all the theme values to apply my base styles. How do I know where it is?

```<code>module.exports = {
  // ...
  plugins: [
    plugin(function ({ addBase, addComponents, addUtilities, theme }) {
      addBase({
        'h1': {
          fontSize: theme('fontSize.2xl'), // need to see more fontSize and properties, where I can see it?
        },
        'h2': {
          fontSize: theme('fontSize.xl'),
        },
      })
    }
  ]
}
</code>```

Body:
I am writing plugin to add custom styles in TailwindCSS, but I am a bit confused with values of theme(). I don't know how to see all the theme values to apply my base styles. How do I know where it is?

module.exports = {
  // ...
  plugins: [
    plugin(function ({ addBase, addComponents, addUtilities, theme }) {
      addBase({
        'h1': {
          fontSize: theme('fontSize.2xl'), // need to see more fontSize and properties, where I can see it?
        },
        'h2': {
          fontSize: theme('fontSize.xl'),
        },
      })
    }
  ]
}


问:
memory size utilize by the structure in c using sizeof opeartor
```<code>`typedef struct emp
{
    char name[2];
    int age;
    double sal;
} e1;

</code>```

int main(){
e1 employee1;
}`

I am expecting the sizeof(employee1) is 14 Bytes. but it is giving me 16 Bytes.
I want to know why is ity 16 Bytes.

Body:
`typedef struct emp
{
    char name[2];
    int age;
    double sal;
} e1;

int main(){
e1 employee1;
}`

I am expecting the sizeof(employee1) is 14 Bytes. but it is giving me 16 Bytes.
I want to know why is ity 16 Bytes.


问:
Simulating energyplus with the BCVTB interface
I have a openstudio model with 3 zones. We are using a python program to execute energyplus with the BCVTB interface. I got it to work on thermal zone 3 but not for thermal zone 1 and 2. I have the input variables defined in variables.cfg as: as:

```<code><variable source="Ptolemy">
    <energyplus <EnergyPlus schedule="Cooling TZ2 Setpoint Schedule"/>
  </variable>
  <variable source="Ptolemy">
    <energyplus <EnergyPlus schedule="Heating TZ2 Setpoint Schedule"/>
  </variable></variable>
</code>```

But when I run the execution I seem to get no load on the Air Loop for thermal zone 2. I have a plant loop for district heating and district cooling and then Air Loops thermal zone 2.

Could use some help with this.

The Osm and idf file can be found here: https://drive.google.com/file/d/1TM6LfmL8KI7w0XFswB9GMTH-KJQE5D-m/view?usp=share_link

Output from energyplus:

```<code>Program Version,EnergyPlus, Version 22.1.0-ed759b17ee, YMD=2022.12.20 10:42,
   ************* Beginning Zone Sizing Calculations
   ** Warning ** SetUpDesignDay: Entered DesignDay Barometric Pressure=31000 differs by more than 10% from Standard Barometric Pressure=100201.
   **   ~~~   ** ...occurs in DesignDay=SIZING PERIOD DESIGN DAY 1, Standard Pressure (based on elevation) will be used.
   ** Warning ** ProcessScheduleInput: Schedule:Compact="ZONE CONTROL TYPE SCHED TZ2", Schedule Type Limits Name="ANY NUMBER" not found -- will not be validated
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS OFF DISCRETE", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS ON CONTINUOUS", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS OFF DISCRETE 1", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS ON CONTINUOUS 1", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** GetHTSurfaceData: Surfaces with interface to Ground found but no "Ground Temperatures" were input.
   **   ~~~   ** Found first in surface=SURFACE 7
   **   ~~~   ** Defaults, constant throughout the year of (18.0) will be used.
   ** Warning ** CheckUsedConstructions: There are 6 nominally unused constructions in input.
   **   ~~~   ** For explicit details on each unused construction, use Output:Diagnostics,DisplayExtraWarnings;
   ** Warning ** Calculated design cooling load for zone=THERMAL ZONE 2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** Calculated design heating load for zone=THERMAL ZONE 2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ************* Beginning System Sizing Calculations
   ** Warning ** ManageSizing: Calculated Cooling Design Air Flow Rate for System=AIR LOOP CLG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** ManageSizing: Calculated Heating Design Air Flow Rate for System=AIR LOOP CLG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** ManageSizing: Calculated Cooling Design Air Flow Rate for System=AIR LOOP HTG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** ManageSizing: Calculated Heating Design Air Flow Rate for System=AIR LOOP HTG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ************* Beginning Plant Sizing Calculations
   ** Severe  ** SizeAirLoopBranches: AirLoopHVAC AIR LOOP CLG TZ2 has air flow less than 1.0000E-003 m3/s.
   **   ~~~   ** Primary air system volumetric flow rate = 0.0000 m3/s.
   **   ~~~   ** Check flow rate inputs for components in this air loop and,
   **   ~~~   ** if autosized, check Sizing:Zone and Sizing:System objects and related inputs.
   **  Fatal  ** Previous condition causes termination.
   ...Summary of Errors that led to program termination:
   ..... Reference severe error count=1
   ..... Last severe error=SizeAirLoopBranches: AirLoopHVAC AIR LOOP CLG TZ2 has air flow less than 1.0000E-003 m3/s.
   ************* Warning:  Node connection errors not checked - most system input has not been read (see previous warning).
   ************* Fatal error -- final processing.  Program exited before simulations began.  See previous error messages.
   *************
   ************* ===== Final Error Summary =====
   ************* The following error categories occurred.  Consider correcting or noting.
   ************* Nominally Unused Constructions
   ************* ..The nominally unused constructions warning is provided to alert you to potential conditions that can cause
   ************* ..extra time during simulation. Each construction is calculated by the algorithm indicated in the HeatBalanceAlgorithm
   ************* ..object. You may remove the constructions indicated (when you use the DisplayExtraWarnings option).
   *************
   ************* EnergyPlus Warmup Error Summary. During Warmup: 0 Warning; 0 Severe Errors.
   ************* EnergyPlus Sizing Error Summary. During Sizing: 14 Warning; 0 Severe Errors.
   ************* EnergyPlus Terminated--Fatal Error Detected. 14 Warning; 1 Severe Errors; Elapsed Time=00hr 00min  0.14sec
</code>```

Thanks

I tried to run a simulation of the 3 thermal zones building using the BCVTB interface of energyplus. I expected the simulation to work since I defined the input variables in the variables.cfg file.

Body:
I have a openstudio model with 3 zones. We are using a python program to execute energyplus with the BCVTB interface. I got it to work on thermal zone 3 but not for thermal zone 1 and 2. I have the input variables defined in variables.cfg as: as:

<variable source="Ptolemy">
    <energyplus <EnergyPlus schedule="Cooling TZ2 Setpoint Schedule"/>
  </variable>
  <variable source="Ptolemy">
    <energyplus <EnergyPlus schedule="Heating TZ2 Setpoint Schedule"/>
  </variable></variable>

But when I run the execution I seem to get no load on the Air Loop for thermal zone 2. I have a plant loop for district heating and district cooling and then Air Loops thermal zone 2.

Could use some help with this.

The Osm and idf file can be found here: https://drive.google.com/file/d/1TM6LfmL8KI7w0XFswB9GMTH-KJQE5D-m/view?usp=share_link

Output from energyplus:

Program Version,EnergyPlus, Version 22.1.0-ed759b17ee, YMD=2022.12.20 10:42,
   ************* Beginning Zone Sizing Calculations
   ** Warning ** SetUpDesignDay: Entered DesignDay Barometric Pressure=31000 differs by more than 10% from Standard Barometric Pressure=100201.
   **   ~~~   ** ...occurs in DesignDay=SIZING PERIOD DESIGN DAY 1, Standard Pressure (based on elevation) will be used.
   ** Warning ** ProcessScheduleInput: Schedule:Compact="ZONE CONTROL TYPE SCHED TZ2", Schedule Type Limits Name="ANY NUMBER" not found -- will not be validated
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS OFF DISCRETE", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS ON CONTINUOUS", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS OFF DISCRETE 1", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** ProcessScheduleInput: Schedule:Constant="ALWAYS ON CONTINUOUS 1", Blank Schedule Type Limits Name input -- will not be validated.
   ** Warning ** GetHTSurfaceData: Surfaces with interface to Ground found but no "Ground Temperatures" were input.
   **   ~~~   ** Found first in surface=SURFACE 7
   **   ~~~   ** Defaults, constant throughout the year of (18.0) will be used.
   ** Warning ** CheckUsedConstructions: There are 6 nominally unused constructions in input.
   **   ~~~   ** For explicit details on each unused construction, use Output:Diagnostics,DisplayExtraWarnings;
   ** Warning ** Calculated design cooling load for zone=THERMAL ZONE 2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** Calculated design heating load for zone=THERMAL ZONE 2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ************* Beginning System Sizing Calculations
   ** Warning ** ManageSizing: Calculated Cooling Design Air Flow Rate for System=AIR LOOP CLG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** ManageSizing: Calculated Heating Design Air Flow Rate for System=AIR LOOP CLG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** ManageSizing: Calculated Cooling Design Air Flow Rate for System=AIR LOOP HTG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ** Warning ** ManageSizing: Calculated Heating Design Air Flow Rate for System=AIR LOOP HTG TZ2 is zero.
   **   ~~~   ** Check Sizing:Zone and ZoneControl:Thermostat inputs.
   ************* Beginning Plant Sizing Calculations
   ** Severe  ** SizeAirLoopBranches: AirLoopHVAC AIR LOOP CLG TZ2 has air flow less than 1.0000E-003 m3/s.
   **   ~~~   ** Primary air system volumetric flow rate = 0.0000 m3/s.
   **   ~~~   ** Check flow rate inputs for components in this air loop and,
   **   ~~~   ** if autosized, check Sizing:Zone and Sizing:System objects and related inputs.
   **  Fatal  ** Previous condition causes termination.
   ...Summary of Errors that led to program termination:
   ..... Reference severe error count=1
   ..... Last severe error=SizeAirLoopBranches: AirLoopHVAC AIR LOOP CLG TZ2 has air flow less than 1.0000E-003 m3/s.
   ************* Warning:  Node connection errors not checked - most system input has not been read (see previous warning).
   ************* Fatal error -- final processing.  Program exited before simulations began.  See previous error messages.
   *************
   ************* ===== Final Error Summary =====
   ************* The following error categories occurred.  Consider correcting or noting.
   ************* Nominally Unused Constructions
   ************* ..The nominally unused constructions warning is provided to alert you to potential conditions that can cause
   ************* ..extra time during simulation. Each construction is calculated by the algorithm indicated in the HeatBalanceAlgorithm
   ************* ..object. You may remove the constructions indicated (when you use the DisplayExtraWarnings option).
   *************
   ************* EnergyPlus Warmup Error Summary. During Warmup: 0 Warning; 0 Severe Errors.
   ************* EnergyPlus Sizing Error Summary. During Sizing: 14 Warning; 0 Severe Errors.
   ************* EnergyPlus Terminated--Fatal Error Detected. 14 Warning; 1 Severe Errors; Elapsed Time=00hr 00min  0.14sec

Thanks

I tried to run a simulation of the 3 thermal zones building using the BCVTB interface of energyplus. I expected the simulation to work since I defined the input variables in the variables.cfg file.


问:
How to calculate payin3 amount using rest api or using javascript in paypal?
I am going to integrate paylater option with payin3. On my website I would like to show instalment process in my own design for which I want to get these amounts (56.65,56.67,56.66) In this case total amount is 170. Can anyone let me know how to achieve this task


问:
PycharmProjects\pythonProject\vencannot be loaded because running scripts is disabled on this system. For more informatio see about_Execution_Policies
I want to install Django on pycharm but when I try to install this massage display:</p>
```<code>File C:\Users\dell\PycharmProjects\pythonProject\venv\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more
information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
    + CategoryInfo          : SecurityError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess
</code>```

Body:
I want to install Django on pycharm but when I try to install this massage display:

File C:\Users\dell\PycharmProjects\pythonProject\venv\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more
information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
    + CategoryInfo          : SecurityError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess


问:
Passing pdf in a post request with other parameters in Flutter
Hello what I am trying to do is create a registration page where user will enter his username , password and attach pdf file for his certificate. I want to send this model to my BE and store it in PostgreSQL. I have used file_picker so I can choose the PDF files and my model looks like this

```<code>class RegistrationModel{
  String username;
  String password;
  FilePickerResult certificate;
}
</code>```

My question is how can I send this in post request, do I need to use MultipartRequest and if so how can I do it. Thanks in advance :)

Body:
Hello what I am trying to do is create a registration page where user will enter his username , password and attach pdf file for his certificate. I want to send this model to my BE and store it in PostgreSQL. I have used file_picker so I can choose the PDF files and my model looks like this

class RegistrationModel{
  String username;
  String password;
  FilePickerResult certificate;
}

My question is how can I send this in post request, do I need to use MultipartRequest and if so how can I do it. Thanks in advance :)


问:
Add substring to an Inner Join
I want to replicate this query in my Power BI:

SELECT n.codigonotario,
       n.nombrenotario,
       CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN COUNT(cp.indiceunico)END AS NUM_OPERACIONES,
       CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN SUM(cp.bases)END AS NUM_BASES,
       SUM(dc.valornumerico / (CASE ISNULL(p.MONEDA, 0)WHEN 0 THEN 166.386 ELSE 1 END)) AS TotalCuantias,
       RTRIM(LTRIM(cp.indiceunico)) AS codigoconcepto,
       cp.textoconcepto + ' (' + RTRIM(LTRIM(cp.indiceunico)) + ')' AS DESCRIPCIONCONCEPTO,
       cdc.categoriacampo
FROM notarios n
     INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
     INNER JOIN conceptosprotocolos cp ON cp.codigoprotocolo = p.codigoprotocolo
     INNER JOIN datosconceptos dc ON dc.codigoprotocolo = p.codigoprotocolo
                                 AND SUBSTRING(cp.path, 6, 4) = SUBSTRING(dc.path, 6, 4)
     INNER JOIN camposdatosconceptos cdc ON cdc.codigocampodatos = dc.codigocampodatos
     INNER JOIN conceptos c ON c.codigoconcepto = cp.codigoconcepto
WHERE p.fechaprotocolo >= '01/01/2022'
  AND p.fechaprotocolo <= '31/12/2022'
  AND n.codigonotario LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
  AND (cdc.categoriacampo = 'CUANTIA'
    OR cdc.categoriacampo = 'HONORARIOSBRUTO'
    OR cdc.categoriacampo = 'HONORARIOSREDUCCION')
  AND p.encargado LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
  AND (p.codigoprotocolo LIKE 'p%'
    OR p.codigoprotocolo LIKE 'c%')
  AND cp.indiceunico LIKE CASE LEN(1)WHEN 0 THEN '%' ELSE 1 END
GROUP BY n.codigonotario,
         n.nombrenotario,
         cp.indiceunico,
         cp.textoconcepto,
         dc.path,
         cdc.categoriacampo;
```
<p>I already have the database and tables imported in my project:</p>
<p><img src="https://i.stack.imgur.com/ivjSH.png" alt="enter image description here" /></p>
<p>And I know how to implement inner joins:
<img src="https://i.stack.imgur.com/4d09P.png" alt="enter image description here" /></p>
<p>But some of those inner joins need substrings and other functions, starting with the first inner join:</p>
```INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
```
<p>You can't use SQL functions in Power BI, but you can use Power Query, so I'm struggling trying to replicate those here (it doesn't recognize 'MID' or 'LEFT').</p>
```let
  Origen = Sql.Databases("LAPTOP-OSCAR"),
  Far = Origen{[Name="Far"]}[Data],
  dbo_NOTARIOS = Far{[Schema="dbo",Item="NOTARIOS"]}[Data],
  #"Consultas combinadas" = Table.NestedJoin(dbo_NOTARIOS, {"CODIGONOTARIO"}, PROTOCOLOS, {"CODIGOPROTOCOLO"}, "PROTOCOLOS", JoinKind.Inner)

in
  #"Consultas combinadas"
```

Could somebody help me to replicate the substring function in Power BI, please?

Title: Add substring to an Inner Join

Body:
I want to replicate this query in my Power BI:

SELECT n.codigonotario,
       n.nombrenotario,
       CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN COUNT(cp.indiceunico)END AS NUM_OPERACIONES,
       CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN SUM(cp.bases)END AS NUM_BASES,
       SUM(dc.valornumerico / (CASE ISNULL(p.MONEDA, 0)WHEN 0 THEN 166.386 ELSE 1 END)) AS TotalCuantias,
       RTRIM(LTRIM(cp.indiceunico)) AS codigoconcepto,
       cp.textoconcepto + ' (' + RTRIM(LTRIM(cp.indiceunico)) + ')' AS DESCRIPCIONCONCEPTO,
       cdc.categoriacampo
FROM notarios n
     INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
     INNER JOIN conceptosprotocolos cp ON cp.codigoprotocolo = p.codigoprotocolo
     INNER JOIN datosconceptos dc ON dc.codigoprotocolo = p.codigoprotocolo
                                 AND SUBSTRING(cp.path, 6, 4) = SUBSTRING(dc.path, 6, 4)
     INNER JOIN camposdatosconceptos cdc ON cdc.codigocampodatos = dc.codigocampodatos
     INNER JOIN conceptos c ON c.codigoconcepto = cp.codigoconcepto
WHERE p.fechaprotocolo >= '01/01/2022'
  AND p.fechaprotocolo <= '31/12/2022'
  AND n.codigonotario LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
  AND (cdc.categoriacampo = 'CUANTIA'
    OR cdc.categoriacampo = 'HONORARIOSBRUTO'
    OR cdc.categoriacampo = 'HONORARIOSREDUCCION')
  AND p.encargado LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
  AND (p.codigoprotocolo LIKE 'p%'
    OR p.codigoprotocolo LIKE 'c%')
  AND cp.indiceunico LIKE CASE LEN(1)WHEN 0 THEN '%' ELSE 1 END
GROUP BY n.codigonotario,
         n.nombrenotario,
         cp.indiceunico,
         cp.textoconcepto,
         dc.path,
         cdc.categoriacampo;

I already have the database and tables imported in my project:

And I know how to implement inner joins:

But some of those inner joins need substrings and other functions, starting with the first inner join:

INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))

You can't use SQL functions in Power BI, but you can use Power Query, so I'm struggling trying to replicate those here (it doesn't recognize 'MID' or 'LEFT').

let
  Origen = Sql.Databases("LAPTOP-OSCAR"),
  Far = Origen{[Name="Far"]}[Data],
  dbo_NOTARIOS = Far{[Schema="dbo",Item="NOTARIOS"]}[Data],
  #"Consultas combinadas" = Table.NestedJoin(dbo_NOTARIOS, {"CODIGONOTARIO"}, PROTOCOLOS, {"CODIGOPROTOCOLO"}, "PROTOCOLOS", JoinKind.Inner)

in
  #"Consultas combinadas"

Could somebody help me to replicate the substring function in Power BI, please?


问:
android dismiss notification bubbles when app resume
I am implements Android Bubbles Notification, I can display bubble success when app in background.

But I want to dismiss the bubble when user open app again, Im tried to using Notification clear all but not wokring

```<code>NotificationManagerCompat.from(this).cancelAll();
</code>```

Can someone give me some advices? Thanks so much

Body:
I am implements Android Bubbles Notification, I can display bubble success when app in background.

But I want to dismiss the bubble when user open app again, Im tried to using Notification clear all but not wokring

NotificationManagerCompat.from(this).cancelAll();

Can someone give me some advices? Thanks so much


问:
How to check filtered item in checkable ComboBox?
If an item in the list is selected using a filter, it becomes non-checkable. For filter I use functions: on_completer_activated, setModel, setModelColumn. I added a filter model to filter matching items (QSortFilterProxyModel), added a completer, which uses the filter model (QCompleter).
On selection of an item from the completer, select the corresponding item from combobox (function "on_completer_activated"); on model change, update the models of the filter and completer as well (function "setModel"); on model column change, update the model column of the filter and completer as well (function "setModelColumn")
How to make it checkable?

```<code>class CheckableComboBox(QComboBox):
    def __init__(self):
        super().__init__()
        self._changed = False
        self.view().pressed.connect(self.handleItemPressed)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setEditable(True)
        self.pFilterModel = QSortFilterProxyModel(self)
        self.pFilterModel.setSourceModel(self.model())
        self.completer = QCompleter(self.pFilterModel, self)
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.setCompleter(self.completer)
        self.lineEdit().textEdited.connect(self.pFilterModel.setFilterFixedString)
        self.completer.activated.connect(self.on_completer_activated)

    def setItemChecked(self, index, checked=False):
        item = self.model().item(index, self.modelColumn()) # QStandardItem object
        if checked:
            item.setCheckState(Qt.Checked)
        else:
            item.setCheckState(Qt.Unchecked)

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)

        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
        else:
            item.setCheckState(Qt.Checked)
        self._changed = True

    def hidePopup(self):
        if not self._changed:
           super().hidePopup()
        self._changed = False

    def itemChecked(self, index):
        item = self.model().item(index, self.modelColumn())
        return item.checkState() == Qt.Checked

    def on_completer_activated(self, text):
        if text:
            index = self.findText(text)
            self.setCurrentIndex(index)
            self.activated[str].emit(self.itemText(index))

    def setModel(self, model):
        super(CheckableComboBox, self).setModel(model)
        self.pFilterModel.setSourceModel(model)
        self.completer.setModel(self.pFilterModel)

    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.pFilterModel.setFilterKeyColumn(column)
        super(CheckableComboBox, self).setModelColumn(column)

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(500, 150)
        mainLayout = QVBoxLayout()
        self.combo = CheckableComboBox()
        mainLayout.addWidget(self.combo)

        for i in range(7):
            self.combo.addItem('Item {0}'.format(str(i)))
            self.combo.setItemChecked(i, False)
            self.setLayout(mainLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet('QWidget {font-size: 40px;}')

    myApp = MyApp()
    myApp.show()
    app.exit(app.exec_())`
</code>```

I'm trying to make a filtered item checkable.

Body:
If an item in the list is selected using a filter, it becomes non-checkable. For filter I use functions: on_completer_activated, setModel, setModelColumn. I added a filter model to filter matching items (QSortFilterProxyModel), added a completer, which uses the filter model (QCompleter).
On selection of an item from the completer, select the corresponding item from combobox (function "on_completer_activated"); on model change, update the models of the filter and completer as well (function "setModel"); on model column change, update the model column of the filter and completer as well (function "setModelColumn")
How to make it checkable?

class CheckableComboBox(QComboBox):
    def __init__(self):
        super().__init__()
        self._changed = False
        self.view().pressed.connect(self.handleItemPressed)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setEditable(True)
        self.pFilterModel = QSortFilterProxyModel(self)
        self.pFilterModel.setSourceModel(self.model())
        self.completer = QCompleter(self.pFilterModel, self)
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.setCompleter(self.completer)
        self.lineEdit().textEdited.connect(self.pFilterModel.setFilterFixedString)
        self.completer.activated.connect(self.on_completer_activated)

    def setItemChecked(self, index, checked=False):
        item = self.model().item(index, self.modelColumn()) # QStandardItem object
        if checked:
            item.setCheckState(Qt.Checked)
        else:
            item.setCheckState(Qt.Unchecked)

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)

        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
        else:
            item.setCheckState(Qt.Checked)
        self._changed = True

    def hidePopup(self):
        if not self._changed:
           super().hidePopup()
        self._changed = False

    def itemChecked(self, index):
        item = self.model().item(index, self.modelColumn())
        return item.checkState() == Qt.Checked

    def on_completer_activated(self, text):
        if text:
            index = self.findText(text)
            self.setCurrentIndex(index)
            self.activated[str].emit(self.itemText(index))

    def setModel(self, model):
        super(CheckableComboBox, self).setModel(model)
        self.pFilterModel.setSourceModel(model)
        self.completer.setModel(self.pFilterModel)

    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.pFilterModel.setFilterKeyColumn(column)
        super(CheckableComboBox, self).setModelColumn(column)

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(500, 150)
        mainLayout = QVBoxLayout()
        self.combo = CheckableComboBox()
        mainLayout.addWidget(self.combo)

        for i in range(7):
            self.combo.addItem('Item {0}'.format(str(i)))
            self.combo.setItemChecked(i, False)
            self.setLayout(mainLayout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet('QWidget {font-size: 40px;}')

    myApp = MyApp()
    myApp.show()
    app.exit(app.exec_())`

I'm trying to make a filtered item checkable.


问:
Devide methods in Resharper's Intellisense to custom groups
please is it possible to somehow tune the Resharper's improved IntelliSense, so it would allow to devide methods to some sections?
Like let's say I have many different methods in a class, and I would like to group them into groups of some functions...
(For example I could have method, that get's some data, I would put like [GetData] attribute above each of a method like this, then let's say I have some Action methods, I would mark all of them with [Action] attribute... Then I could have like veryfing methods, I would mark them with [Verify] attribute, and I could have some methods completely hidden from IntelliSense, so I would just mark them with [Hidden] attribute...
And then, Resharper would cleverly devide these methods in IntelliSense to these groups, so the user of my class can see much more clearly, what can be done with the class.
Would something like this be possible?
Thanks sooo much, I will greatly appreciate any help :)

EDIT: It could even divide methods to different sections based on whether they are actually defined in this class, or whether they are inherited from the base class.

EDIT 2: It could also work even more intelligently, in a way that you could define not only groups, but alse subgroups. So let's say, I have 10 Action methods in my class, but logically, they can even be grouped into 3 subgroups, so I would divide them again, so it is even more simple and understandable for the user of my class :)


问:
Insert/Update/Delete rows to an existing table by checking the received data in SQL Server
I have an employee transactional table with millions of records. I have a requirement to check the newly arrived data to verify any change in the existing record for same employee. If there is a change then update the existing data. If it's not present then delete the existing record. If its new insert it. If no change keep as it is.

I have implemented this with checksum-based approach, however, its quite time consuming. I am not preferring MERGE based approach due to performance constraints. Is there is any other built-in function based approach can suggest?


问:
How to detect if my code was started by rider or visual-studio
In general my program should do the same whether it's started from within the Visual Studio IDE or the Rider IDE. However some things are different, e.g. in VS I want to send dbg output to System.Diagnostics.Debug while in Rider I want to use Console because Riders debug output view is cluttered with things I'm not interested in.

So I have a static method DebugHelper.WriteLine and in that method I want to detect whether I'm running inside Rider or VS or none of them. How can I find that out?


问:
Azure springboot distributed tracing correlationId and application map issue
I have created and configured two spring boot applications and with the help of application insight and cloud sleuth maven dependencies I have configured the logback . When I started the applications from my Intellij and queried the logs from applicationInsights -> logs I was able to see the traces and logs along with the operation_id, operation_name, cloud_RoleName and other values etc..

But when I look into the application map for the tracing graph I could see the two application instances as below but that is not connected with the correlation. I tried everything and it is not working. Any help would be much appreciated. Thanks in advance.


问:
Can third party cookies wipe out first party cookies due to reaching browser cookie limits?
Can third party cookies wipe out first party cookies due to reaching browser cookie limits?

Let's say I set important first party cookie SESSIONID. I want to know if it can be wiped out by lots of third party cookies set by script from other domain? (for example if the website relies on ads to provide revenue, those third party script usually set quite a lot of third party cookies).

I know that the fresh first party cookies can wipe out older first party cookies if they reach that limit. However I don't know how it applies to third party cookies.


问:
How to pass integer variable as an argument
I am trying to pass integer that appears in a loop as an argument. So I am trying something like this:

```<code>for(;$i -le $n;$i++){

   Start-Process -FilePath "C:\Program Files\app.exe" -ArgumentList "--config-$i"
}
</code>```

I have found a solution in a way that I convert integer to string and that works but I was wondering if there is a cleaner/better way to do this? Mainly because it would make my code cleaner because I wouldn't have to convert every time I want to do something like this.

Body:
I am trying to pass integer that appears in a loop as an argument. So I am trying something like this:

for(;$i -le $n;$i++){

   Start-Process -FilePath "C:\Program Files\app.exe" -ArgumentList "--config-$i"
}

I have found a solution in a way that I convert integer to string and that works but I was wondering if there is a cleaner/better way to do this? Mainly because it would make my code cleaner because I wouldn't have to convert every time I want to do something like this.


问:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'modal')
I'm trying to install @mui/x-date-pickers to my project and I followed the instructions from their website, which you can find here. The problem is when i installed everything and added this code to my project

```<code>import React from 'react';
import { LocalizationProvider, TimePicker } from '@mui/x-date-pickers';
import { TextField } from '@mui/material';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
import moment from 'moment';

export const Blabla = () => {
   const [value, setValue] = React.useState(moment('2014-08-18T21:11:54'));

   const handleChange = (newValue: any) => {
      setValue(newValue);
   };
   return (
      <LocalizationProvider dateAdapter={AdapterMoment}>
         <TimePicker
            label="Time"
            value={value}
            onChange={handleChange}
            renderInput={(params) => <TextField {...params} />}
         />
       </LocalizationProvider>
    );
};
</code>```

I am getting this error

And this is how my dependencies look like in the package.json file

```<code>"dependencies": {
  "@mui/x-date-pickers": "^5.0.11",
  "auth0-js": "^9.13.2",
  "axios": "^0.19.2",
  "copy-webpack-plugin": "6",
  "crossfilter": "^1.3.12",
  "crossfilter2": "^1.5.4",
  "cubejs": "^1.3.2",
  "d3": "^6.2.0",
  "dataloader": "^2.0.0",
  "date-fns": "^2.14.0",
  "emotion": "^10.0.27",
  "emotion-theming": "^10.0.27",
  "highcharts": "8.1.2",
  "highcharts-custom-events": "3.0.9",
  "highcharts-react-official": "3.0.0",
  "html-to-image": "^1.10.8",
  "i18next": "^19.4.4",
  "js-sha256": "^0.9.0",
  "json2mq": "^0.2.0",
  "jspdf": "^2.5.1",
  "jsverify": "^0.8.4",
  "leaflet": "^1.7.1",
  "mixpanel-browser": "2.41.0",
  "moment": "^2.25.3",
  "papaparse": "^5.3.0",
  "patch-package": "^6.4.7",
  "ramda": "^0.27.0",
  "react": "^16.13.1",
  "react-codemirror": "^1.0.0",
  "react-copy-to-clipboard": "^5.0.2",
  "react-csv": "^2.0.3",
  "react-dates": "^21.8.0",
  "react-datetime": "^3.0.4",
  "react-dom": "^16.13.1",
  "react-dropzone": "^12.0.1",
  "react-email-editor": "^1.2.0",
  "react-hot-loader": "^4.12.21",
  "react-hot-toast": "^2.2.0",
  "react-i18next": "^11.4.0",
  "react-infinite-scroll-component": "^5.1.0",
  "react-leaflet": "^2.7.0",
  "react-material-ui-carousel": "^2.3.11",
  "react-router-dom": "^5.2.0",
  "react-slick": "^0.26.1",
  "react-tooltip": "^4.2.11",
  "rxjs": "^6.5.5",
  "slick-carousel": "^1.8.1",
  "topojson-client": "^3.1.0",
  "urlencode": "^1.1.0",
  "webpack": "^4.42.1"
},
"devDependencies": {
  "@babel/core": "^7.12.3",
  "@babel/plugin-proposal-class-properties": "^7.8.3",
  "@babel/plugin-proposal-optional-chaining": "^7.9.0",
  "@babel/plugin-syntax-dynamic-import": "^7.8.3",
  "@babel/plugin-transform-react-jsx": "^7.9.4",
  "@babel/plugin-transform-runtime": "^7.9.0",
  "@babel/preset-env": "^7.9.5",
  "@babel/preset-typescript": "^7.9.0",
  "@cubejs-client/core": "^0.25.0",
  "@date-io/moment": "^2.16.1",
  "@emotion/babel-plugin": "^11.7.2",
  "@emotion/core": "10.1.1",
  "@emotion/react": "^11.10.5",
  "@emotion/styled": "^10.0.27",
  "@material-ui/core": "^4.9.11",
  "@material-ui/icons": "^4.9.1",
  "@material-ui/lab": "^4.0.0-alpha.53",
  "@mui/material": "^5.11.1",
  "@storybook/addon-actions": "^5.3.18",
  "@storybook/addon-console": "^1.2.1",
  "@storybook/addon-knobs": "^5.3.18",
  "@storybook/addon-storyshots": "^5.3.18",
  "@storybook/addon-viewport": "^5.3.18",
  "@storybook/react": "^5.3.18",
  "@svgr/webpack": "^5.3.1",
  "@testing-library/jest-dom": "^5.5.0",
  "@testing-library/react": "^10.0.4",
  "@types/auth0-js": "^9.12.4",
  "@types/d3": "^5.16.3",
  "@types/geojson": "^7946.0.7",
  "@types/jest": "25.2.1",
  "@types/json2mq": "^0.2.0",
  "@types/jspdf": "^1.3.3",
  "@types/leaflet": "^1.5.17",
  "@types/lodash": "4.14.151",
  "@types/mixpanel-browser": "2.35.6",
  "@types/node": "^17.0.17",
  "@types/papaparse": "^5.2.5",
  "@types/ramda": "0.27.6",
  "@types/react": "^16.9.34",
  "@types/react-codemirror": "^1.0.3",
  "@types/react-copy-to-clipboard": "^4.3.0",
  "@types/react-csv": "^1.1.1",
  "@types/react-dates": "^17.1.10",
  "@types/react-dom": "^16.9.6",
  "@types/react-email-editor": "^1.1.1",
  "@types/react-leaflet": "^2.5.2",
  "@types/react-router-dom": "^5.1.5",
  "@types/react-slick": "^0.23.4",
  "@types/testing-library__react": "^10.0.1",
  "@types/urlencode": "^1.1.2",
  "@types/webpack-env": "^1.16.3",
  "@typescript-eslint/eslint-plugin": "^5.33.1",
  "@typescript-eslint/parser": "^5.33.1",
  "autoprefixer": "^9.7.6",
  "babel-eslint": "10.1.0",
  "babel-loader": "^8.1.0",
  "babel-plugin-emotion": "^10.0.33",
  "babel-preset-react-app": "^9.1.2",
  "css-loader": "^3.5.3",
  "eslint": "7.1.0",
  "eslint-config-prettier": "6.10.1",
  "eslint-import-resolver-jest": "3.0.0",
  "eslint-import-resolver-webpack": "0.12.1",
  "eslint-plugin-import": "2.21.2",
  "eslint-plugin-react": "7.19.0",
  "eslint-plugin-react-hooks": "4.0.2",
  "html-webpack-plugin": "^4.2.1",
  "husky": "^7.0.4",
  "jest": "25.2.1",
  "jest-emotion": "^10.0.32",
  "lint-staged": "^10.1.6",
  "npx": "^10.2.2",
  "postcss-loader": "^3.0.0",
  "postcss-preset-env": "^6.7.0",
  "react-test-renderer": "^16.13.1",
  "storybook-addon-emotion-theme": "^2.1.1",
  "storybook-addon-jsx": "^7.2.3",
  "style-loader": "^1.2.1",
  "ts-jest": "^25.4.0",
  "typescript": "4.6",
  "typescript-styled-plugin": "^0.15.0",
  "url-loader": "^4.1.0",
  "webpack-cli": "^3.3.11",
  "webpack-dev-server": "^3.10.3"
},
</code>```

What am I doing wrong?

Body:
I'm trying to install @mui/x-date-pickers to my project and I followed the instructions from their website, which you can find here. The problem is when i installed everything and added this code to my project

import React from 'react';
import { LocalizationProvider, TimePicker } from '@mui/x-date-pickers';
import { TextField } from '@mui/material';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
import moment from 'moment';

export const Blabla = () => {
   const [value, setValue] = React.useState(moment('2014-08-18T21:11:54'));

   const handleChange = (newValue: any) => {
      setValue(newValue);
   };
   return (
      <LocalizationProvider dateAdapter={AdapterMoment}>
         <TimePicker
            label="Time"
            value={value}
            onChange={handleChange}
            renderInput={(params) => <TextField {...params} />}
         />
       </LocalizationProvider>
    );
};

I am getting this error

And this is how my dependencies look like in the package.json file

"dependencies": {
  "@mui/x-date-pickers": "^5.0.11",
  "auth0-js": "^9.13.2",
  "axios": "^0.19.2",
  "copy-webpack-plugin": "6",
  "crossfilter": "^1.3.12",
  "crossfilter2": "^1.5.4",
  "cubejs": "^1.3.2",
  "d3": "^6.2.0",
  "dataloader": "^2.0.0",
  "date-fns": "^2.14.0",
  "emotion": "^10.0.27",
  "emotion-theming": "^10.0.27",
  "highcharts": "8.1.2",
  "highcharts-custom-events": "3.0.9",
  "highcharts-react-official": "3.0.0",
  "html-to-image": "^1.10.8",
  "i18next": "^19.4.4",
  "js-sha256": "^0.9.0",
  "json2mq": "^0.2.0",
  "jspdf": "^2.5.1",
  "jsverify": "^0.8.4",
  "leaflet": "^1.7.1",
  "mixpanel-browser": "2.41.0",
  "moment": "^2.25.3",
  "papaparse": "^5.3.0",
  "patch-package": "^6.4.7",
  "ramda": "^0.27.0",
  "react": "^16.13.1",
  "react-codemirror": "^1.0.0",
  "react-copy-to-clipboard": "^5.0.2",
  "react-csv": "^2.0.3",
  "react-dates": "^21.8.0",
  "react-datetime": "^3.0.4",
  "react-dom": "^16.13.1",
  "react-dropzone": "^12.0.1",
  "react-email-editor": "^1.2.0",
  "react-hot-loader": "^4.12.21",
  "react-hot-toast": "^2.2.0",
  "react-i18next": "^11.4.0",
  "react-infinite-scroll-component": "^5.1.0",
  "react-leaflet": "^2.7.0",
  "react-material-ui-carousel": "^2.3.11",
  "react-router-dom": "^5.2.0",
  "react-slick": "^0.26.1",
  "react-tooltip": "^4.2.11",
  "rxjs": "^6.5.5",
  "slick-carousel": "^1.8.1",
  "topojson-client": "^3.1.0",
  "urlencode": "^1.1.0",
  "webpack": "^4.42.1"
},
"devDependencies": {
  "@babel/core": "^7.12.3",
  "@babel/plugin-proposal-class-properties": "^7.8.3",
  "@babel/plugin-proposal-optional-chaining": "^7.9.0",
  "@babel/plugin-syntax-dynamic-import": "^7.8.3",
  "@babel/plugin-transform-react-jsx": "^7.9.4",
  "@babel/plugin-transform-runtime": "^7.9.0",
  "@babel/preset-env": "^7.9.5",
  "@babel/preset-typescript": "^7.9.0",
  "@cubejs-client/core": "^0.25.0",
  "@date-io/moment": "^2.16.1",
  "@emotion/babel-plugin": "^11.7.2",
  "@emotion/core": "10.1.1",
  "@emotion/react": "^11.10.5",
  "@emotion/styled": "^10.0.27",
  "@material-ui/core": "^4.9.11",
  "@material-ui/icons": "^4.9.1",
  "@material-ui/lab": "^4.0.0-alpha.53",
  "@mui/material": "^5.11.1",
  "@storybook/addon-actions": "^5.3.18",
  "@storybook/addon-console": "^1.2.1",
  "@storybook/addon-knobs": "^5.3.18",
  "@storybook/addon-storyshots": "^5.3.18",
  "@storybook/addon-viewport": "^5.3.18",
  "@storybook/react": "^5.3.18",
  "@svgr/webpack": "^5.3.1",
  "@testing-library/jest-dom": "^5.5.0",
  "@testing-library/react": "^10.0.4",
  "@types/auth0-js": "^9.12.4",
  "@types/d3": "^5.16.3",
  "@types/geojson": "^7946.0.7",
  "@types/jest": "25.2.1",
  "@types/json2mq": "^0.2.0",
  "@types/jspdf": "^1.3.3",
  "@types/leaflet": "^1.5.17",
  "@types/lodash": "4.14.151",
  "@types/mixpanel-browser": "2.35.6",
  "@types/node": "^17.0.17",
  "@types/papaparse": "^5.2.5",
  "@types/ramda": "0.27.6",
  "@types/react": "^16.9.34",
  "@types/react-codemirror": "^1.0.3",
  "@types/react-copy-to-clipboard": "^4.3.0",
  "@types/react-csv": "^1.1.1",
  "@types/react-dates": "^17.1.10",
  "@types/react-dom": "^16.9.6",
  "@types/react-email-editor": "^1.1.1",
  "@types/react-leaflet": "^2.5.2",
  "@types/react-router-dom": "^5.1.5",
  "@types/react-slick": "^0.23.4",
  "@types/testing-library__react": "^10.0.1",
  "@types/urlencode": "^1.1.2",
  "@types/webpack-env": "^1.16.3",
  "@typescript-eslint/eslint-plugin": "^5.33.1",
  "@typescript-eslint/parser": "^5.33.1",
  "autoprefixer": "^9.7.6",
  "babel-eslint": "10.1.0",
  "babel-loader": "^8.1.0",
  "babel-plugin-emotion": "^10.0.33",
  "babel-preset-react-app": "^9.1.2",
  "css-loader": "^3.5.3",
  "eslint": "7.1.0",
  "eslint-config-prettier": "6.10.1",
  "eslint-import-resolver-jest": "3.0.0",
  "eslint-import-resolver-webpack": "0.12.1",
  "eslint-plugin-import": "2.21.2",
  "eslint-plugin-react": "7.19.0",
  "eslint-plugin-react-hooks": "4.0.2",
  "html-webpack-plugin": "^4.2.1",
  "husky": "^7.0.4",
  "jest": "25.2.1",
  "jest-emotion": "^10.0.32",
  "lint-staged": "^10.1.6",
  "npx": "^10.2.2",
  "postcss-loader": "^3.0.0",
  "postcss-preset-env": "^6.7.0",
  "react-test-renderer": "^16.13.1",
  "storybook-addon-emotion-theme": "^2.1.1",
  "storybook-addon-jsx": "^7.2.3",
  "style-loader": "^1.2.1",
  "ts-jest": "^25.4.0",
  "typescript": "4.6",
  "typescript-styled-plugin": "^0.15.0",
  "url-loader": "^4.1.0",
  "webpack-cli": "^3.3.11",
  "webpack-dev-server": "^3.10.3"
},

What am I doing wrong?


问:
ERROR: could not open file ""C:\Users\Zadane\Downloads\Popdata.csv" for reading: No such file or directory

I am login to a database su -postgres

psql

\c postgres  # connected to database

Successfully Created table population

I have a CSV file and I have successfully created table, when I am trying to use the copy command

```<code>COPY population(year,age,ethnic,sex,area,count)
FROM 'C:\Users\Zadane\Downloads\Popdata.csv'  #( note my CSV file is in my download folders )
DELIMITER ‘,’
CSV HEADER**;
</code>```

I get and error,

CSV HEADER;ERROR:  syntax error at or near "pwd"
LINE 1: pwd

When, I remove the Delimiter from the command, I get an error

ERROR:  could not open file "C:\Users\Zadane\Downloads\Popdata.csv"
for reading: No such file or directory**

```<code>\! pwd -shows displays the name:- /home/postgres
</code>```

SHOW data_directory shows path:- /usr/local/postgresql/pgsql/data.

Can you let me know how to resolve the issue.or how to move .csv file to the /usr/local/postgres path,  Or if there is any manually command where i can enter 70 to 80k records in a table.

Body:
I am login to a database su -postgres

psql

\c postgres  # connected to database

Successfully Created table population

I have a CSV file and I have successfully created table, when I am trying to use the copy command

COPY population(year,age,ethnic,sex,area,count)
FROM 'C:\Users\Zadane\Downloads\Popdata.csv'  #( note my CSV file is in my download folders )
DELIMITER ‘,’
CSV HEADER**;

I get and error,

CSV HEADER;ERROR:  syntax error at or near "pwd"
LINE 1: pwd

When, I remove the Delimiter from the command, I get an error

ERROR:  could not open file "C:\Users\Zadane\Downloads\Popdata.csv"
for reading: No such file or directory**

\! pwd -shows displays the name:- /home/postgres

SHOW data_directory shows path:- /usr/local/postgresql/pgsql/data.

Can you let me know how to resolve the issue.or how to move .csv file to the /usr/local/postgres path,  Or if there is any manually command where i can enter 70 to 80k records in a table.


问:
react jest test fail when try mock useContext and MaterialUI
Hello i have this component

`

```<code>import { useContext } from 'react'
import { ProductContext } from '../../context/ProductContext'
import InfoSale from './InfoSale'
import { Grid } from '@mui/material'
import Description from './Description'

const ProductDetail = () => {
  const { productDetail } = useContext(ProductContext)
  const { currency_id, price, title, sold_quantity, pictures, condition, plain_text } = productDetail

  return (
    Object.keys(productDetail).length > 0 &&
    <Grid container sx={{display: 'flex', justifyContent:'center', flexDirection:'row', pt:'32px'}}>
      <Grid item xs={8}>
        <img src={pictures[0].url} alt={title} />
      </Grid>
      <Grid item xs={4} style={{display: 'flex', flexDirection:'column'}}>
        <InfoSale
          title={title}
          condition={condition}
          soldQuantity={sold_quantity}
          currencyId={currency_id}
          price={price}
        />
      </Grid>
      <Grid item xs={8} style={{ paddingLeft: '32px',display:'flex', marginTop: '32px' }}>
        <Description description={plain_text} />
      </Grid>
      <Grid item xs={4}/>
    </Grid>
  )
}

export default ProductDetail
</code>```

`

and when i try to do the test

`

```<code>import React from "react"
import { render, screen } from "@testing-library/react"
import ProductDetail from "../../src/components/productDetail/ProductDetail";

describe('test component <ProductDetail />', () => {
  const mockUseContext = jest.spyOn(React, "useContext");
  mockUseContext.mockReturnValue({
    productDetail :  {
      currency_id: 'ARS',
      price: 10000,
      title: 'Example product',
      sold_quantity: 5,
      pictures: [{ url: 'http://example.com/image.jpg' }],
      condition: 'new',
      plain_text: 'This is an example product',
      }
  });

   test('init', () => {
    render(<ProductDetail  />)
    screen.debug()
  })
})

</code>```

`

if i put a console.log in the component i recive the context mock but i have the next error
Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'MuiGrid-root')]

if i remove all relate in the component of materialui and replace with divs, the test pass, but i need material for the proyect, any idea?

test component in react that read data from context and render the result using material ui, i already done mock the context but the test fail with material

Body:
Hello i have this component

`

import { useContext } from 'react'
import { ProductContext } from '../../context/ProductContext'
import InfoSale from './InfoSale'
import { Grid } from '@mui/material'
import Description from './Description'

const ProductDetail = () => {
  const { productDetail } = useContext(ProductContext)
  const { currency_id, price, title, sold_quantity, pictures, condition, plain_text } = productDetail

  return (
    Object.keys(productDetail).length > 0 &&
    <Grid container sx={{display: 'flex', justifyContent:'center', flexDirection:'row', pt:'32px'}}>
      <Grid item xs={8}>

      </Grid>
      <Grid item xs={4} style={{display: 'flex', flexDirection:'column'}}>
        <InfoSale
          title={title}
          condition={condition}
          soldQuantity={sold_quantity}
          currencyId={currency_id}
          price={price}
        />
      </Grid>
      <Grid item xs={8} style={{ paddingLeft: '32px',display:'flex', marginTop: '32px' }}>
        <Description description={plain_text} />
      </Grid>
      <Grid item xs={4}/>
    </Grid>
  )
}

export default ProductDetail

`

and when i try to do the test

`

import React from "react"
import { render, screen } from "@testing-library/react"
import ProductDetail from "../../src/components/productDetail/ProductDetail";

describe('test component <ProductDetail />', () => {
  const mockUseContext = jest.spyOn(React, "useContext");
  mockUseContext.mockReturnValue({
    productDetail :  {
      currency_id: 'ARS',
      price: 10000,
      title: 'Example product',
      sold_quantity: 5,
      pictures: [{ url: 'http://example.com/image.jpg' }],
      condition: 'new',
      plain_text: 'This is an example product',
      }
  });

   test('init', () => {
    render(<ProductDetail  />)
    screen.debug()
  })
})

`

if i put a console.log in the component i recive the context mock but i have the next error
Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'MuiGrid-root')]

if i remove all relate in the component of materialui and replace with divs, the test pass, but i need material for the proyect, any idea?

test component in react that read data from context and render the result using material ui, i already done mock the context but the test fail with material


问:
Is there an way to reconfigure `_sysconfigdata.py` or to let it contain dynamic values?
Maybe this is a typical "you're doing it wrong" situation - in this case please let me know.

Currently I'm re-using a pre-built Python among different installations located in different directories, and to make this work I need to modify the generated _sysconfigdata.py to contain a certain installation path, which is also available as an environment variable (here SOME_ENV).

This can be done by search/replace a __PLACEHOLDER__ (configured with --prefix) inside _sysconfigdata.py, like this:

'INCLUDEPY': '__PLACEHOLDER__/include/python3.10',
```
<p>.. with something dynamic like this:</p>
<pre class="lang-py prettyprint-override"><code>'INCLUDEPY': f"{os.environ['SOME_ENV']}/include/python3.10",
</code>```

Direct references of environment variables like

'INCLUDEPY': "${SOME_ENV}/include/python3.10",
```

seem to not work.

This of course feels like an ugly workaround for the built-in way to say "please take this pre-built Python and re-configure the prefix I've provided with configure.

Is there a way to "reconfigure" a readily built Python to be located in a different path?

(Background: I need those values in order to be able to build Python packages from source inside a delivered Python installation)

Body:
Maybe this is a typical "you're doing it wrong" situation - in this case please let me know.

Currently I'm re-using a pre-built Python among different installations located in different directories, and to make this work I need to modify the generated _sysconfigdata.py to contain a certain installation path, which is also available as an environment variable (here SOME_ENV).

This can be done by search/replace a __PLACEHOLDER__ (configured with --prefix) inside _sysconfigdata.py, like this:

'INCLUDEPY': '__PLACEHOLDER__/include/python3.10',

.. with something dynamic like this:

'INCLUDEPY': f"{os.environ['SOME_ENV']}/include/python3.10",

Direct references of environment variables like

'INCLUDEPY': "${SOME_ENV}/include/python3.10",

seem to not work.

This of course feels like an ugly workaround for the built-in way to say "please take this pre-built Python and re-configure the prefix I've provided with configure.

Is there a way to "reconfigure" a readily built Python to be located in a different path?

(Background: I need those values in order to be able to build Python packages from source inside a delivered Python installation)


问:
How to make transactions running a particular query execute sequentially in Neo4j?
I'm working on an app where users can un-bookmark a post they've bookmarked before. But I realized that if multiple requests is sent by a particular user to un-bookmark a post they've bookmarked before, node properties get set multiple times. For example, if user 1 bookmarked post 1, their noOfBookmarks (both user and post) will increase by 1 and when they un-bookmark, their noOfBookmarks will decrease by 1. But sometimes during concurrent requests, I get incorrect or negative noOfBookmarks depending on the number of requests. I'm using MATCH which will return 0 rows when the pattern can't be found.

I think the problem is because of the isolation level neo4j is using. During concurrent requests, the changes made by the first query to run will not be visible to other transactions until the first transaction is committed. So the MATCH is still returning rows, that's why I'm getting invalid properties. I think what I need is for transactions to be executed sequentially or get an exclusive read lock.

I've tried setting a property on the user and post node (before MATCHing the bookmark relationship) which will make the first transaction get a write lock on those nodes. I thought other transactions will wait at this point for the write lock to be released before continuing but it didn't work.

How do I ensure the first transaction during concurrent requests modify the graph and other transactions stop at that MATCH (which is the behaviour during sequential requests)?

This is my cypher query:

```<code>MATCH (user:User { id: $userId })
MATCH (post:Post { id: $postId })
WITH user, post
MATCH (user)-[bookmarkRel:BOOKMARKED_POST]->(post)
WITH bookmarkRel, user, post
DELETE bookmarkRel
WITH post, user
SET post.noOfBookmarks = post.noOfBookmarks - 1,
    user.noOfBookmarks = user.noOfBookmarks - 1
RETURN post { .* }
</code>```

Thank you

Body:
I'm working on an app where users can un-bookmark a post they've bookmarked before. But I realized that if multiple requests is sent by a particular user to un-bookmark a post they've bookmarked before, node properties get set multiple times. For example, if user 1 bookmarked post 1, their noOfBookmarks (both user and post) will increase by 1 and when they un-bookmark, their noOfBookmarks will decrease by 1. But sometimes during concurrent requests, I get incorrect or negative noOfBookmarks depending on the number of requests. I'm using MATCH which will return 0 rows when the pattern can't be found.

I think the problem is because of the isolation level neo4j is using. During concurrent requests, the changes made by the first query to run will not be visible to other transactions until the first transaction is committed. So the MATCH is still returning rows, that's why I'm getting invalid properties. I think what I need is for transactions to be executed sequentially or get an exclusive read lock.

I've tried setting a property on the user and post node (before MATCHing the bookmark relationship) which will make the first transaction get a write lock on those nodes. I thought other transactions will wait at this point for the write lock to be released before continuing but it didn't work.

How do I ensure the first transaction during concurrent requests modify the graph and other transactions stop at that MATCH (which is the behaviour during sequential requests)?

This is my cypher query:

MATCH (user:User { id: $userId })
MATCH (post:Post { id: $postId })
WITH user, post
MATCH (user)-[bookmarkRel:BOOKMARKED_POST]->(post)
WITH bookmarkRel, user, post
DELETE bookmarkRel
WITH post, user
SET post.noOfBookmarks = post.noOfBookmarks - 1,
    user.noOfBookmarks = user.noOfBookmarks - 1
RETURN post { .* }

Thank you