问:
torch parameter is going to nan when after first optim.step() while doing GPT's downstream task

Foundation

I'm doing finetuning with GPTJForCausalLM. (pretrained is 6B and fp16).

Environment

ubuntu 20.04 (nvidia-docker)

cuda(in docker) version is 11.4

RTX 3090 (24G VRAM)

torch.__version__  1.12.1

transformers.__version__  4.12.5

jupyter lab version : 3.5.0
python3 version : Python 3.7.13

pretrained model : (kakao-kogpt 6B 16fp) https://github.com/kakaobrain/kogpt

Problem

If I freeze some layer's parameters and doing model.forward()-loss.backward()-optim.step(), then not freezed parameters are gone to nan. Only first step enough to make nan.

Question

Why I can get this error?. Many of internet search result cannot help me.

Bug reproduction Code

```<code>!git clone https://github.com/kakaobrain/kogpt.git
!pip install -r ./kogpt/requirements.txt

from transformers import GPTJForCausalLM
from transformers import AutoTokenizer, AutoModelForCausalLM
import transformers
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import copy
import inspect
import torch.optim as optim
import types
import re
import numpy as np

#model github's official code, and it works well.
tokenizer = AutoTokenizer.from_pretrained(
      'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16',  # or float32 version: revision=KoGPT6B-ryan1.5b
      bos_token='[BOS]', eos_token='[EOS]', unk_token='[UNK]', pad_token='[PAD]', mask_token='[MASK]'
    )

model = AutoModelForCausalLM.from_pretrained(
      'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16',  # or float32 version: revision=KoGPT6B-ryan1.5b
      pad_token_id=tokenizer.eos_token_id,
      torch_dtype='auto', low_cpu_mem_usage=True
    )

#for working test, I just freeze all layers but not freeze last layer.
ls = list(model.modules())
for i, m in enumerate(ls):
    if i == len(ls) - 1:
        #unfreeze for last layer
        m.requires_grad_(True)
    else:
        #freeze other layers
        m.requires_grad_(False)

optim = optim.AdamW(model.parameters(), lr=1e-5)
_ = model.cuda()
_ = model.train()

sample = ['Some text data for finetuning-1', 'Some text data for finetuning-2']
with torch.cuda.amp.autocast(): #this line is not affect change result.
    #make batch
    batch = tokenizer(sample, padding=True, truncation=True, max_length=64, return_tensors='pt')
    batch = {k:v.cuda() for k, v in batch.items()}

    #forward
    out = model(**batch)

    #loss
    loss = F.cross_entropy(out.logits[:, :-1, :].flatten(0,-2),
                       batch['input_ids'][:,1:].flatten(),
                       reduction='mean')

print(loss.grad)
#None <- result

print(loss.is_leaf)
#False <- result

print(loss)
#tensor(6.6850, device='cuda:0', grad_fn=<NllLossBackward0>) <- result

print(list(model.parameters())[-1])
#Parameter containing: <- result
#tensor([-0.0454,  0.0815, -0.0442,  ..., -0.0566, -0.0557, -0.0552],
#       device='cuda:0', dtype=torch.float16, requires_grad=True)

loss.backward()

print(loss.grad)
#None <- print result

print(loss.is_leaf)
#False <- print result

print(list(model.parameters())[-1])
#Parameter containing: <- result
#tensor([-0.0454,  0.0815, -0.0442,  ..., -0.0566, -0.0557, -0.0552],
#       device='cuda:0', dtype=torch.float16, requires_grad=True)

optim.step()

print(list(model.parameters())[-1])
#Parameter containing: <- result, this is the problem point.
#tensor([   nan, 0.0815,    nan,  ...,    nan,    nan,    nan], device='cuda:0',
#       dtype=torch.float16, requires_grad=True)
</code>```

More Information

The work I really wanted to do is using LoRA downstream.

I did it first time with this code.

```<code>#(... same as section 5.)

#load model
model = AutoModelForCausalLM.from_pretrained(
      'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16',  # or float32 version: revision=KoGPT6B-ryan1.5b
      pad_token_id=tokenizer.eos_token_id,
      torch_dtype='auto', low_cpu_mem_usage=True
    )

#my lora adapter adder code, (refer to https://github.com/huggingface/transformers/issues/14839)
def forward_linear_with_adapter(self, input: torch.Tensor) -> torch.Tensor:
    #replace NN.Linear's forward()
    out = F.linear(input, self.weight, self.bias)
    if self.lora_adapter:
        out += self.lora_adapter(input)
    return out

def AddLoRAtoLinear(layer, adapter_dim=16, _dtype=None):
    #add adapter
    dt = _dtype if _dtype else layer._parameters['weight'].dtype
    layer.lora_adapter = nn.Sequential(
        nn.Linear(layer.in_features, adapter_dim, bias=False, dtype=dt),
        nn.Linear(adapter_dim, layer.out_features, bias=False, dtype=dt)
    )
    #make trainable
    layer.lora_adapter.requires_grad_(True)
    nn.init.zeros_(layer.lora_adapter[1].weight)

    #bind forward with adapter
    layer.forward = types.MethodType(forward_linear_with_adapter, layer)

def forward_embedding_with_adapter(self, input: torch.Tensor) -> torch.Tensor:
    #replace NN.Embedding's forward()
    out = F.embedding(input, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse)
    if self.lora_adapter:
        out += self.lora_adapter(input)
    return out

def AddLoRAtoEmbedding(layer, adapter_dim=16, _dtype=None):
    dt = _dtype if _dtype else layer._parameters['weight'].dtype
    #add adapter
    layer.lora_adapter = nn.Sequential(
        nn.Embedding(layer.num_embeddings, adapter_dim, dtype=dt),
        nn.Linear(adapter_dim, layer.embedding_dim, bias=False, dtype=dt)
    )
    #make trainable
    layer.lora_adapter.requires_grad_(True)
    nn.init.zeros_(layer.lora_adapter[1].weight) #follow LoRA paper's

    #bind forward with adapter
    layer.forward = types.MethodType(forward_embedding_with_adapter, layer)

def MakeLoRA(model):
    #freeze all other parameters.
    for _ in model.parameters():
        _.requires_grad_(False)

    #apply LoRA only embedding & linear layers.
    needchange = []
    for module in model.modules():
        if type(module) == nn.Linear or type(module) == nn.Embedding:
            needchange.append(module)

    for module in needchange:
        if type(module) == nn.Linear:
            #run custom LoRA attach function to this layer
            AddLoRAtoLinear(module)
        elif type(module) == nn.Embedding:
            #run custom LoRA attach function to this layer
            AddLoRAtoEmbedding(module)
    return model

if False:
  #instead of doing this(from code in section 5), do MakeLoRA()
  ls = list(model.modules())
  for i, m in enumerate(ls):
      if i == len(ls) - 1:
          #unfreeze for last layer
          m.requires_grad_(True)
      else:
          #freeze other layers
          m.requires_grad_(False)
else:
  #change model to has LoRA
  model = MakeLoRA(model)

#(and do it same as section 5... and make same nan error )
</code>```

Body:
Foundation

I'm doing finetuning with GPTJForCausalLM. (pretrained is 6B and fp16).

Environment

ubuntu 20.04 (nvidia-docker)

cuda(in docker) version is 11.4

RTX 3090 (24G VRAM)

torch.__version__  1.12.1

transformers.__version__  4.12.5

jupyter lab version : 3.5.0
python3 version : Python 3.7.13

pretrained model : (kakao-kogpt 6B 16fp) https://github.com/kakaobrain/kogpt

Problem

If I freeze some layer's parameters and doing model.forward()-loss.backward()-optim.step(), then not freezed parameters are gone to nan. Only first step enough to make nan.

Question

Why I can get this error?. Many of internet search result cannot help me.

Bug reproduction Code

!git clone https://github.com/kakaobrain/kogpt.git
!pip install -r ./kogpt/requirements.txt

from transformers import GPTJForCausalLM
from transformers import AutoTokenizer, AutoModelForCausalLM
import transformers
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import copy
import inspect
import torch.optim as optim
import types
import re
import numpy as np

#model github's official code, and it works well.
tokenizer = AutoTokenizer.from_pretrained(
      'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16',  # or float32 version: revision=KoGPT6B-ryan1.5b
      bos_token='[BOS]', eos_token='[EOS]', unk_token='[UNK]', pad_token='[PAD]', mask_token='[MASK]'
    )

model = AutoModelForCausalLM.from_pretrained(
      'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16',  # or float32 version: revision=KoGPT6B-ryan1.5b
      pad_token_id=tokenizer.eos_token_id,
      torch_dtype='auto', low_cpu_mem_usage=True
    )

#for working test, I just freeze all layers but not freeze last layer.
ls = list(model.modules())
for i, m in enumerate(ls):
    if i == len(ls) - 1:
        #unfreeze for last layer
        m.requires_grad_(True)
    else:
        #freeze other layers
        m.requires_grad_(False)

optim = optim.AdamW(model.parameters(), lr=1e-5)
_ = model.cuda()
_ = model.train()

sample = ['Some text data for finetuning-1', 'Some text data for finetuning-2']
with torch.cuda.amp.autocast(): #this line is not affect change result.
    #make batch
    batch = tokenizer(sample, padding=True, truncation=True, max_length=64, return_tensors='pt')
    batch = {k:v.cuda() for k, v in batch.items()}

    #forward
    out = model(**batch)

    #loss
    loss = F.cross_entropy(out.logits[:, :-1, :].flatten(0,-2),
                       batch['input_ids'][:,1:].flatten(),
                       reduction='mean')

print(loss.grad)
#None <- result

print(loss.is_leaf)
#False <- result

print(loss)
#tensor(6.6850, device='cuda:0', grad_fn=<NllLossBackward0>) <- result

print(list(model.parameters())[-1])
#Parameter containing: <- result
#tensor([-0.0454,  0.0815, -0.0442,  ..., -0.0566, -0.0557, -0.0552],
#       device='cuda:0', dtype=torch.float16, requires_grad=True)

loss.backward()

print(loss.grad)
#None <- print result

print(loss.is_leaf)
#False <- print result

print(list(model.parameters())[-1])
#Parameter containing: <- result
#tensor([-0.0454,  0.0815, -0.0442,  ..., -0.0566, -0.0557, -0.0552],
#       device='cuda:0', dtype=torch.float16, requires_grad=True)

optim.step()

print(list(model.parameters())[-1])
#Parameter containing: <- result, this is the problem point.
#tensor([   nan, 0.0815,    nan,  ...,    nan,    nan,    nan], device='cuda:0',
#       dtype=torch.float16, requires_grad=True)

More Information

The work I really wanted to do is using LoRA downstream.

I did it first time with this code.

#(... same as section 5.)

#load model
model = AutoModelForCausalLM.from_pretrained(
      'kakaobrain/kogpt', revision='KoGPT6B-ryan1.5b-float16',  # or float32 version: revision=KoGPT6B-ryan1.5b
      pad_token_id=tokenizer.eos_token_id,
      torch_dtype='auto', low_cpu_mem_usage=True
    )

#my lora adapter adder code, (refer to https://github.com/huggingface/transformers/issues/14839)
def forward_linear_with_adapter(self, input: torch.Tensor) -> torch.Tensor:
    #replace NN.Linear's forward()
    out = F.linear(input, self.weight, self.bias)
    if self.lora_adapter:
        out += self.lora_adapter(input)
    return out

def AddLoRAtoLinear(layer, adapter_dim=16, _dtype=None):
    #add adapter
    dt = _dtype if _dtype else layer._parameters['weight'].dtype
    layer.lora_adapter = nn.Sequential(
        nn.Linear(layer.in_features, adapter_dim, bias=False, dtype=dt),
        nn.Linear(adapter_dim, layer.out_features, bias=False, dtype=dt)
    )
    #make trainable
    layer.lora_adapter.requires_grad_(True)
    nn.init.zeros_(layer.lora_adapter[1].weight)

    #bind forward with adapter
    layer.forward = types.MethodType(forward_linear_with_adapter, layer)

def forward_embedding_with_adapter(self, input: torch.Tensor) -> torch.Tensor:
    #replace NN.Embedding's forward()
    out = F.embedding(input, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse)
    if self.lora_adapter:
        out += self.lora_adapter(input)
    return out

def AddLoRAtoEmbedding(layer, adapter_dim=16, _dtype=None):
    dt = _dtype if _dtype else layer._parameters['weight'].dtype
    #add adapter
    layer.lora_adapter = nn.Sequential(
        nn.Embedding(layer.num_embeddings, adapter_dim, dtype=dt),
        nn.Linear(adapter_dim, layer.embedding_dim, bias=False, dtype=dt)
    )
    #make trainable
    layer.lora_adapter.requires_grad_(True)
    nn.init.zeros_(layer.lora_adapter[1].weight) #follow LoRA paper's

    #bind forward with adapter
    layer.forward = types.MethodType(forward_embedding_with_adapter, layer)

def MakeLoRA(model):
    #freeze all other parameters.
    for _ in model.parameters():
        _.requires_grad_(False)

    #apply LoRA only embedding & linear layers.
    needchange = []
    for module in model.modules():
        if type(module) == nn.Linear or type(module) == nn.Embedding:
            needchange.append(module)

    for module in needchange:
        if type(module) == nn.Linear:
            #run custom LoRA attach function to this layer
            AddLoRAtoLinear(module)
        elif type(module) == nn.Embedding:
            #run custom LoRA attach function to this layer
            AddLoRAtoEmbedding(module)
    return model

if False:
  #instead of doing this(from code in section 5), do MakeLoRA()
  ls = list(model.modules())
  for i, m in enumerate(ls):
      if i == len(ls) - 1:
          #unfreeze for last layer
          m.requires_grad_(True)
      else:
          #freeze other layers
          m.requires_grad_(False)
else:
  #change model to has LoRA
  model = MakeLoRA(model)

#(and do it same as section 5... and make same nan error )


来源: stackexchange

问:
WineBottler returning error message every time i try an open .exe file on Mac
I'm trying to open a plugin for SNAP (to process Sentinel-3 imagery) on my Mac - the plugin downloads as an .exe file which means I need to open it using WineBottler. Every time I try and open the file however, I get this error message:

```<code>###BOTTLING### default.sh
/var/folders/rz/rr6ytzhx5gl60f1v1tbc67xm0000gn/T/AppTranslocation/6CDA1855-FA78-4A2A-A976-2C1A539F36ED/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources/bottler.sh: line 39: /Applications/Wine.app/Contents/Resources/bin/wine: Bad CPU type in executable
###BOTTLING### Gathering debug Info...

Versions
OS...........................: darwin21
Wine.........................:
WineBottler..................: 1.8.6
Wineticks....................: 20220411-next - sha256sum: b6370f13c4dc410023f2a4e4e9a4385d2a0420031666c2f30befccc9b39c8f65

Environment
PWD..........................: '/Applications/Wine.app/Contents/Resources/bin'
PATH.........................: /Applications/Wine.app/Contents/Resources/bin:/usr/bin:/bin:/usr/sbin:/sbin
USER.........................: hannah
HOME.........................: /Users/hannah
COMPUTERNAME.................: hannahâs MacBook Air
BUNDLERESOURCEPATH...........: /var/folders/rz/rr6ytzhx5gl60f1v1tbc67xm0000gn/T/AppTranslocation/6CDA1855-FA78-4A2A-A976-2C1A539F36ED/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources
WINEPREFIX...................: /Applications/Wine.app/Contents/Resources
WINEPATH.....................: /Applications/Wine.app/Contents/Resources/bin
LD_LIBRARY_PATH..............: /Applications/Wine.app/Contents/Resources/lib:/opt/X11/lib:/usr/X11/lib
DYLD_FALLBACK_LIBRARY_PATH...: /Applications/Wine.app/Contents/Resources/lib:/usr/lib:/opt/X11/lib:/usr/X11/lib
SILENT.......................:
http_proxy...................:
https_proxy..................:
ftp_proxy....................:
socks5_proxy.................:

Bottle
TEMPLATE.....................:
BOTTLE.......................: /Users/hannah/Desktop/Untitled.app
INSTALLER_URL................: /Users/hannah/Desktop/iCOR_Setup_3.0.0.exe
INSTALLER_IS_ZIPPED..........: 0
INSTALLER_NAME...............: iCOR_Setup_3.0.0.exe
INSTALLER_ARGUMENTS..........:
REMOVE_MONO..................:
REMOVE_GECKO.................:
REMOVE_USERS.................:
REMOVE_INSTALLERS............:
WINETRICKS_ITEMS.............: winxp
DLL_OVERRIDES................:
EXECUTABLE_PATH..............: winefile
EXECUTABLE_ARGUMENTS.........:
EXECUTABLE_VERSION...........: 1.0.0
BUNDLE_COPYRIGHT.............: Â© Your Company
BUNDLE_IDENTIFIER............: com.yourcompany.yourapp
BUNDLE_CATEGORYTYPE..........: public.app-category.business
SILENT.......................:

Hardware:

    Hardware Overview:

      Model Name: MacBook Air
      Model Identifier: MacBookAir7,2
      Processor Name: Dual-Core Intel Core i5
      Processor Speed: 1.6 GHz
      Number of Processors: 1
      Total Number of Cores: 2
      L2 Cache (per Core): 256 KB
      L3 Cache: 3 MB
      Hyper-Threading Technology: Enabled
      Memory: 4 GB
      System Firmware Version: 476.0.0.0.0
      OS Loader Version: 540.120.3~22
      SMC Version (system): 2.27f2
      Serial Number (system): C02QM1XWG941
      Hardware UUID: EE27242F-C2B2-59E6-AAED-D598D1D61044
      Provisioning UDID: EE27242F-C2B2-59E6-AAED-D598D1D61044

###BOTTLING### Create .app...
###BOTTLING### Enabling CoreAudio, Colors, Antialiasing  and flat menus...
/var/folders/rz/rr6ytzhx5gl60f1v1tbc67xm0000gn/T/AppTranslocation/6CDA1855-FA78-4A2A-A976-2C1A539F36ED/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources/bottler.sh: line 134: /Applications/Wine.app/Contents/Resources/bin/wine: Bad CPU type in executable
### LOG ### Command '/Applications/Wine.app/Contents/Resources/bin/wine regedit /tmp/reg.reg' returned status 126.

###ERROR### Command '/Applications/Wine.app/Contents/Resources/bin/wine regedit /tmp/reg.reg' returned status 126.
Task returned with status 1.
</code>```

I've tried downloading the 'stable' version of WineBottler, download and redownload it to no avail - it always returns this message. I can't seem to find any way of getting around this or recently posted question (a lot are from 2010-15 and are outdated in their solutions)

Does anyone know what I can do to get around this and open it? It's driving me insane!!!
Thanks!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to open a plugin for SNAP (to process Sentinel-3 imagery) on my Mac - the plugin downloads as an .exe file which means I need to open it using WineBottler. Every time I try and open the file however, I get this error message:

###BOTTLING### default.sh
/var/folders/rz/rr6ytzhx5gl60f1v1tbc67xm0000gn/T/AppTranslocation/6CDA1855-FA78-4A2A-A976-2C1A539F36ED/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources/bottler.sh: line 39: /Applications/Wine.app/Contents/Resources/bin/wine: Bad CPU type in executable
###BOTTLING### Gathering debug Info...

Versions
OS...........................: darwin21
Wine.........................:
WineBottler..................: 1.8.6
Wineticks....................: 20220411-next - sha256sum: b6370f13c4dc410023f2a4e4e9a4385d2a0420031666c2f30befccc9b39c8f65

Environment
PWD..........................: '/Applications/Wine.app/Contents/Resources/bin'
PATH.........................: /Applications/Wine.app/Contents/Resources/bin:/usr/bin:/bin:/usr/sbin:/sbin
USER.........................: hannah
HOME.........................: /Users/hannah
COMPUTERNAME.................: hannahâs MacBook Air
BUNDLERESOURCEPATH...........: /var/folders/rz/rr6ytzhx5gl60f1v1tbc67xm0000gn/T/AppTranslocation/6CDA1855-FA78-4A2A-A976-2C1A539F36ED/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources
WINEPREFIX...................: /Applications/Wine.app/Contents/Resources
WINEPATH.....................: /Applications/Wine.app/Contents/Resources/bin
LD_LIBRARY_PATH..............: /Applications/Wine.app/Contents/Resources/lib:/opt/X11/lib:/usr/X11/lib
DYLD_FALLBACK_LIBRARY_PATH...: /Applications/Wine.app/Contents/Resources/lib:/usr/lib:/opt/X11/lib:/usr/X11/lib
SILENT.......................:
http_proxy...................:
https_proxy..................:
ftp_proxy....................:
socks5_proxy.................:

Bottle
TEMPLATE.....................:
BOTTLE.......................: /Users/hannah/Desktop/Untitled.app
INSTALLER_URL................: /Users/hannah/Desktop/iCOR_Setup_3.0.0.exe
INSTALLER_IS_ZIPPED..........: 0
INSTALLER_NAME...............: iCOR_Setup_3.0.0.exe
INSTALLER_ARGUMENTS..........:
REMOVE_MONO..................:
REMOVE_GECKO.................:
REMOVE_USERS.................:
REMOVE_INSTALLERS............:
WINETRICKS_ITEMS.............: winxp
DLL_OVERRIDES................:
EXECUTABLE_PATH..............: winefile
EXECUTABLE_ARGUMENTS.........:
EXECUTABLE_VERSION...........: 1.0.0
BUNDLE_COPYRIGHT.............: Â© Your Company
BUNDLE_IDENTIFIER............: com.yourcompany.yourapp
BUNDLE_CATEGORYTYPE..........: public.app-category.business
SILENT.......................:

Hardware:

    Hardware Overview:

      Model Name: MacBook Air
      Model Identifier: MacBookAir7,2
      Processor Name: Dual-Core Intel Core i5
      Processor Speed: 1.6 GHz
      Number of Processors: 1
      Total Number of Cores: 2
      L2 Cache (per Core): 256 KB
      L3 Cache: 3 MB
      Hyper-Threading Technology: Enabled
      Memory: 4 GB
      System Firmware Version: 476.0.0.0.0
      OS Loader Version: 540.120.3~22
      SMC Version (system): 2.27f2
      Serial Number (system): C02QM1XWG941
      Hardware UUID: EE27242F-C2B2-59E6-AAED-D598D1D61044
      Provisioning UDID: EE27242F-C2B2-59E6-AAED-D598D1D61044

###BOTTLING### Create .app...
###BOTTLING### Enabling CoreAudio, Colors, Antialiasing  and flat menus...
/var/folders/rz/rr6ytzhx5gl60f1v1tbc67xm0000gn/T/AppTranslocation/6CDA1855-FA78-4A2A-A976-2C1A539F36ED/d/WineBottler.app/Contents/Frameworks/WBottler.framework/Resources/bottler.sh: line 134: /Applications/Wine.app/Contents/Resources/bin/wine: Bad CPU type in executable
### LOG ### Command '/Applications/Wine.app/Contents/Resources/bin/wine regedit /tmp/reg.reg' returned status 126.

###ERROR### Command '/Applications/Wine.app/Contents/Resources/bin/wine regedit /tmp/reg.reg' returned status 126.
Task returned with status 1.

I've tried downloading the 'stable' version of WineBottler, download and redownload it to no avail - it always returns this message. I can't seem to find any way of getting around this or recently posted question (a lot are from 2010-15 and are outdated in their solutions)

Does anyone know what I can do to get around this and open it? It's driving me insane!!!
Thanks!


问:
How to work on dynamic properties of an array of objects in javascript?
Please tell me how to remove the key value pair which is having 0 value of capacity like in example

```<code>"10:00-11:00": "0", "11:00-12:00": "0" & "13:00-14:00":"0".
</code>```

What is the logic to check the value of dynamic property?

```<code>clinicOperationMap = [
    {
     "visitDate":"2022-01-22",
     "capacity": {
        "9:00-10:00": "3",
        "10:00-11:00": "0"
      }
    },
    {
     "visitDate":"2022-01-23",
     "capacity": {
        "9:00-10:00": "3",
        "11:00-12:00": "0"
      }
    },
    {
     "visitDate":"2022-01-24",
     "capacity": {
        "9:00-10:00":"3",
        "13:00-14:00":"0"
      }
    },
];
</code>```

I am not getting  how to access those value of dynamic property

Body:
Please tell me how to remove the key value pair which is having 0 value of capacity like in example

"10:00-11:00": "0", "11:00-12:00": "0" & "13:00-14:00":"0".

What is the logic to check the value of dynamic property?

clinicOperationMap = [
    {
     "visitDate":"2022-01-22",
     "capacity": {
        "9:00-10:00": "3",
        "10:00-11:00": "0"
      }
    },
    {
     "visitDate":"2022-01-23",
     "capacity": {
        "9:00-10:00": "3",
        "11:00-12:00": "0"
      }
    },
    {
     "visitDate":"2022-01-24",
     "capacity": {
        "9:00-10:00":"3",
        "13:00-14:00":"0"
      }
    },
];

I am not getting  how to access those value of dynamic property


问:
How to get bit size of an enum, or of a struct bit field?
Is there a way to access the "bit size" of a struct bit field, or the bit range of an enum?

```<code>#include <climits>
#include <iostream>
#include <utility>

template <typename T>
auto bitsizeof() {
    return sizeof(T) * CHAR_BIT;
}

struct Foo {
    unsigned vi : 6;
};

enum Bar { zero = 0, seven = 7 }; // bit-range is 3.

int main() {
    std::cout << "char is        " << bitsizeof<char>() << "\n";
    std::cout << "int is         " << bitsizeof<int>() << "\n";
    std::cout << "long double is " << bitsizeof<long double>() << "\n";

    // Aww.
    std::cout << "Foo::vi is     " << bitsizeof<decltype(std::declval<Foo>().vi)>() << " (ought to be 6)\n";

    // Aww.
    std::cout << "Bar is         " << bitsizeof<Bar>() << " (ought to be 3)\n";
}

/* OUTPUT
char is        8
int is         32
long double is 128
Foo::vi is     32 (ought to be 6)
Bar is         32 (ought to be 3)
*/
</code>```

If there is not a general way to retrieve the bit size of those things at compile time — or calculate it at runtime — my workaround is constexpr std::size_t Bar_bitsize = 3; and constexpr std::size_t Foo_vi_bitsize = 6; and calculate them manually and hard-code them.  But that feels brittle.

UPDATE: additional information.

In C++ (not in C) an enum that does not specify backing storage has a bit range based on its enum members.  It is undefined behavior to set an enum to a value outside of its bit range.

Body:
Is there a way to access the "bit size" of a struct bit field, or the bit range of an enum?

#include <climits>
#include <iostream>
#include <utility>

template <typename T>
auto bitsizeof() {
    return sizeof(T) * CHAR_BIT;
}

struct Foo {
    unsigned vi : 6;
};

enum Bar { zero = 0, seven = 7 }; // bit-range is 3.

int main() {
    std::cout << "char is        " << bitsizeof<char>() << "\n";
    std::cout << "int is         " << bitsizeof<int>() << "\n";
    std::cout << "long double is " << bitsizeof<long double>() << "\n";

    // Aww.
    std::cout << "Foo::vi is     " << bitsizeof<decltype(std::declval<Foo>().vi)>() << " (ought to be 6)\n";

    // Aww.
    std::cout << "Bar is         " << bitsizeof<Bar>() << " (ought to be 3)\n";
}

/* OUTPUT
char is        8
int is         32
long double is 128
Foo::vi is     32 (ought to be 6)
Bar is         32 (ought to be 3)
*/

If there is not a general way to retrieve the bit size of those things at compile time — or calculate it at runtime — my workaround is constexpr std::size_t Bar_bitsize = 3; and constexpr std::size_t Foo_vi_bitsize = 6; and calculate them manually and hard-code them.  But that feels brittle.

UPDATE: additional information.

In C++ (not in C) an enum that does not specify backing storage has a bit range based on its enum members.  It is undefined behavior to set an enum to a value outside of its bit range.


问:
Gradle cannot find the symbol for methods, even if the methods exist. What can I do?
I had a Maven project, which I then switched to Gradle. I am now attempting to compile the Gradle project, but it isn't compiling. For every method, Gradle says that it cannot find the symbol.
In my Calendar.java class, here's what it says:

        Main instance = Main.getInstance();
                            ^
  symbol:   method getInstance()
  location: class Main
```
<p>Maven used to compile the project fine, and the method <code>getInstance()</code> has always existed in the Main class. What can I do to fix this?</p>
<p>For reference, it's a multi-project build. Here's my build.gradle for the mother project:</p>
<pre class="lang-clj prettyprint-override"><code>plugins {
    id "java"
    id "com.github.johnrengelman.shadow" version "7.1.2"
    id "war"
}

group "net.pixlies"
version "1.0-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

subprojects {
    compileJava.options.encoding = "UTF-8"

    apply plugin: "java"
    apply plugin: "war"
    apply plugin: "com.github.johnrengelman.shadow"
}

repositories {
    mavenCentral()
    maven { url "https://repo.purpurmc.org/snapshots/" }
    maven { url "https://repo.extendedclip.com/content/repositories/placeholderapi/" }
    maven { url "https://repo.aikar.co/content/groups/aikar/" }
    maven { url "https://repo.dmulloy2.net/repository/public/" }
}

dependencies {
    implementation "org.mongodb:mongo-java-driver:3.12.11"
    implementation "commons-io:commons-io:2.11.0"
    implementation "co.aikar:acf-paper:0.5.1-SNAPSHOT"
    implementation "org.ocpsoft.prettytime:prettytime:5.0.3.Final"
    implementation "commons-lang:commons-lang:2.6"
}
</code>```

This is the build.gradle of one of my modules, PixliesCore:

plugins {
    id 'net.pixlies.java-conventions'
}

dependencies {
    implementation 'com.github.stefvanschie.inventoryframework:IF:0.10.7'
    implementation 'org.projectlombok:lombok:1.18.24'
    implementation 'redis.clients:jedis:4.2.3'
    implementation 'joda-time:joda-time:2.11.1'
    compileOnly 'org.purpurmc.purpur:purpur-api:1.19-R0.1-SNAPSHOT'
    compileOnly 'com.comphenix.protocol:ProtocolLib:4.7.0'
    compileOnly 'me.clip:placeholderapi:2.11.2'
}

description = 'PixliesCore'
```
<p>This is the console output for <code>./gradlew assemble</code></p>
```> Task :PixliesCore:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':PixliesCore:compileJava'.
> invalid source release: 16

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 11s
11 actionable tasks: 6 executed, 5 up-to-date
```

I notice that it says "invalid source release: 16," perhaps it is the problem. How would I fix this?

Body:
I had a Maven project, which I then switched to Gradle. I am now attempting to compile the Gradle project, but it isn't compiling. For every method, Gradle says that it cannot find the symbol.
In my Calendar.java class, here's what it says:

        Main instance = Main.getInstance();
                            ^
  symbol:   method getInstance()
  location: class Main

Maven used to compile the project fine, and the method getInstance() has always existed in the Main class. What can I do to fix this?

For reference, it's a multi-project build. Here's my build.gradle for the mother project:

plugins {
    id "java"
    id "com.github.johnrengelman.shadow" version "7.1.2"
    id "war"
}

group "net.pixlies"
version "1.0-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

subprojects {
    compileJava.options.encoding = "UTF-8"

    apply plugin: "java"
    apply plugin: "war"
    apply plugin: "com.github.johnrengelman.shadow"
}

repositories {
    mavenCentral()
    maven { url "https://repo.purpurmc.org/snapshots/" }
    maven { url "https://repo.extendedclip.com/content/repositories/placeholderapi/" }
    maven { url "https://repo.aikar.co/content/groups/aikar/" }
    maven { url "https://repo.dmulloy2.net/repository/public/" }
}

dependencies {
    implementation "org.mongodb:mongo-java-driver:3.12.11"
    implementation "commons-io:commons-io:2.11.0"
    implementation "co.aikar:acf-paper:0.5.1-SNAPSHOT"
    implementation "org.ocpsoft.prettytime:prettytime:5.0.3.Final"
    implementation "commons-lang:commons-lang:2.6"
}

This is the build.gradle of one of my modules, PixliesCore:

plugins {
    id 'net.pixlies.java-conventions'
}

dependencies {
    implementation 'com.github.stefvanschie.inventoryframework:IF:0.10.7'
    implementation 'org.projectlombok:lombok:1.18.24'
    implementation 'redis.clients:jedis:4.2.3'
    implementation 'joda-time:joda-time:2.11.1'
    compileOnly 'org.purpurmc.purpur:purpur-api:1.19-R0.1-SNAPSHOT'
    compileOnly 'com.comphenix.protocol:ProtocolLib:4.7.0'
    compileOnly 'me.clip:placeholderapi:2.11.2'
}

description = 'PixliesCore'

This is the console output for ./gradlew assemble

> Task :PixliesCore:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':PixliesCore:compileJava'.
> invalid source release: 16

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 11s
11 actionable tasks: 6 executed, 5 up-to-date

I notice that it says "invalid source release: 16," perhaps it is the problem. How would I fix this?


问:
Different rmse value for every run while optimizing Recurrent Neural Network
I am trying to use Genetic Algorithm for optimizing Recurrent Neural Network.

For this I followed the Python codes mentioned here: http://aqibsaeed.github.io/2017-08-11-genetic-algorithm-for-optimizing-rnn/

The population, genrations and gene legth is mentioned as such:

```<code>population_size = 4
num_generations = 4
gene_length = 10
</code>```

I have observed that every time the codes are run, different values of rmse are obtained.

In the beginning, seed is called for reproducibility of results which is mentioned as such:

```<code>np.random.seed(1120)
</code>```

However, this does not work.

Can somebody please let me know, how do I maintain the reproducibility of the results?

Body:
I am trying to use Genetic Algorithm for optimizing Recurrent Neural Network.

For this I followed the Python codes mentioned here: http://aqibsaeed.github.io/2017-08-11-genetic-algorithm-for-optimizing-rnn/

The population, genrations and gene legth is mentioned as such:

population_size = 4
num_generations = 4
gene_length = 10

I have observed that every time the codes are run, different values of rmse are obtained.

In the beginning, seed is called for reproducibility of results which is mentioned as such:

np.random.seed(1120)

However, this does not work.

Can somebody please let me know, how do I maintain the reproducibility of the results?


问:
PyQt6 / Matplotlib - multiple FigureCanvasQTAgg using one single Figure object
I have an application where the user can open / close many windows containing different plots. At first I attempted to use a new Matplotlib Figure for each window but I had trouble releasing the memory when closing a window with a plot.

An option I am looking at is using a separate FigureCanvasQTAgg for each window and having them share one single Figure. The problem then becomes that if I clear and replot the figure for one window it affects all others.

My question is the following - is there a way to "freeze" a FigureCanvasQTAgg once it has been drawn so that it is not updated when the Figure is cleared / replotted?

One idea I had was to use an EventFilter to catch and stop the paint event for the FigureCanvasQTAgg once it has been drawn so that it is no longer repainted. However I have not been able to make it work. I have not used EventFilter before so I may be doing it incorrectly.

Here is the code, using a simple example with 2 windows using one single Figure. When the second window is plotted the first window gets cleared, which is what I want to avoid. If anyone can spot what's wrong or suggest another way to prevent the first window to be redrawn when the second one is plotted it would be great.

```<code>import sys
import random
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt6 import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class Canvas(FigureCanvas):

    def __init__(self,fig):

        self.paint_enabled = True

        super().__init__(fig)

        self.installEventFilter(self)

    def eventFilter(self, object, event):

        if object == self and event.type() == QtCore.QEvent.Type.Paint and not self.paint_enabled:

            return False

        return super().eventFilter(object,event)

app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QMainWindow()

fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)

xdata = list(range(50))
ydata = [random.randint(0, 10) for i in range(50)]

ax.plot(xdata,ydata)

c1 = Canvas(fig)
c1.move(100,100)
c1.draw()
c1.show()

c1.paint_enabled = False

def second_plot():

    ydata = [random.randint(0, 10) for i in range(50)]

    ax.clear()
    ax.plot(xdata,ydata)

    c2 = Canvas(fig)

    c2.move(600,600)
    c2.draw()
    c2.show()

timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(second_plot)
timer.start(1000)

app.exec()
</code>```

Body:
I have an application where the user can open / close many windows containing different plots. At first I attempted to use a new Matplotlib Figure for each window but I had trouble releasing the memory when closing a window with a plot.

An option I am looking at is using a separate FigureCanvasQTAgg for each window and having them share one single Figure. The problem then becomes that if I clear and replot the figure for one window it affects all others.

My question is the following - is there a way to "freeze" a FigureCanvasQTAgg once it has been drawn so that it is not updated when the Figure is cleared / replotted?

One idea I had was to use an EventFilter to catch and stop the paint event for the FigureCanvasQTAgg once it has been drawn so that it is no longer repainted. However I have not been able to make it work. I have not used EventFilter before so I may be doing it incorrectly.

Here is the code, using a simple example with 2 windows using one single Figure. When the second window is plotted the first window gets cleared, which is what I want to avoid. If anyone can spot what's wrong or suggest another way to prevent the first window to be redrawn when the second one is plotted it would be great.

import sys
import random
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt6 import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class Canvas(FigureCanvas):

    def __init__(self,fig):

        self.paint_enabled = True

        super().__init__(fig)

        self.installEventFilter(self)

    def eventFilter(self, object, event):

        if object == self and event.type() == QtCore.QEvent.Type.Paint and not self.paint_enabled:

            return False

        return super().eventFilter(object,event)

app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QMainWindow()

fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)

xdata = list(range(50))
ydata = [random.randint(0, 10) for i in range(50)]

ax.plot(xdata,ydata)

c1 = Canvas(fig)
c1.move(100,100)
c1.draw()
c1.show()

c1.paint_enabled = False

def second_plot():

    ydata = [random.randint(0, 10) for i in range(50)]

    ax.clear()
    ax.plot(xdata,ydata)

    c2 = Canvas(fig)

    c2.move(600,600)
    c2.draw()
    c2.show()

timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(second_plot)
timer.start(1000)

app.exec()


问:
`yarn global add remotedev-server` gives error `Usage Error: The 'yarn global' commands have been removed in 2.x - use 'yarn dlx' instead`
I am trying to run a local Dev build of Metamask Chrome Extension.
According to their README files Yarn3 should be installed and then to run React Dev Tools and Redux Dev Tools you to have install remotedev-server package with yarn global.
Yarn returns the following error - Usage Error: The 'yarn global' commands have been removed in 2.x - consider using 'yarn dlx' or a third-party plugin instead

Using yarn dlx does not help it gives the following error (see image) my Terminal output logs

I have tried installing the classic yarn that has version 1.22.19 but MetaMask package.json file has locked the yarn version at 3.2.4.

Has anyone faced this issue. Am I missing something. I have tried following one github discussion about this but with no success.


问:
Getting Youtube title in Javascript/NodeJs just won't be synchronous

The problem

I am making a music player for friends. One person is the host, only they play the music, and others just paste a Youtube link, and then it gets sent through a Node.Js server.

I am using embedded Youtube videos to play the music. I am getting the Youtube video id from the links, and just adding them onto the embed link.

I want to make a playlist feature, so that people can see what videos are next. I have multiple Youtube ids, so getting the titles should be easy as that, because tools were already made for this scenario.

These tools are pretty simple: you have the Youtube id, and maybe you need a Youtube API key as well, but then you can console.log() the data.

But when I want to display the data other than logging it onto the console, it just breaks. The application won't wait until the gather ends. It just returns undefined.

I've tried server-side, and client-side versions too, both failed. Javascript never waits.

And I don't want to use PHP, I want to stay with Js/NodeJs/jQuery.

What I've tried

Node.js

The get-youtube-title npm package;

const titles = [];
getYoutubeTitle(videoid, api-key, function(err, title) {
    console.log(title); // this only logs data when collected.
    titles.push(title); // this pushes too early, and does not wait until the data is collected.
}
console.log(titles[0]);
```
<p>This next code is from this post</p>
<pre class="lang-js prettyprint-override"><code>console.log(get_title(video-id));
async function get_title(video-id) {
    // this also doesn't work. returns undefined.
    await getYoutubeTitle(video-id, api-key, (e, t) => {
        return this.title = t
    });
}
</code>```

When using your own API key, it gets the titles accurately. What I've learned when researching for this, is that Node.js is asynchronous (this is my first node.js project, don't judge me), so it kind of makes sense.

I've tried a couple more packages, but those also failed.

ytdl-core from this post

a fork of the original get-youtube-title npm-package, get-youtube-title-await

always using this setup:

const titles = [];
// geting title with some npm-package and pushing data in titles;
console.log(titles[0]); // undefined
```

jQuery

That is when I've switched to the client. I am using socket.io, and I've found out that this is also async both on client and server.
I've tried this answer on stackoverflow, and same issue.

Even though Javascript should be single-threaded, so it should wait, right?

I am using google's cdn.

I don't really want to use jQuery, but if only this version works, jQuery answers are appreciated.

Conclusion

Console.log()-ing always works! It always waits until the data is collected!

I just want to change a div's innerText, and it returns undefined.

Body:
The problem

I am making a music player for friends. One person is the host, only they play the music, and others just paste a Youtube link, and then it gets sent through a Node.Js server.

I am using embedded Youtube videos to play the music. I am getting the Youtube video id from the links, and just adding them onto the embed link.

I want to make a playlist feature, so that people can see what videos are next. I have multiple Youtube ids, so getting the titles should be easy as that, because tools were already made for this scenario.

These tools are pretty simple: you have the Youtube id, and maybe you need a Youtube API key as well, but then you can console.log() the data.

But when I want to display the data other than logging it onto the console, it just breaks. The application won't wait until the gather ends. It just returns undefined.

I've tried server-side, and client-side versions too, both failed. Javascript never waits.

And I don't want to use PHP, I want to stay with Js/NodeJs/jQuery.

What I've tried

Node.js

The get-youtube-title npm package;

const titles = [];
getYoutubeTitle(videoid, api-key, function(err, title) {
    console.log(title); // this only logs data when collected.
    titles.push(title); // this pushes too early, and does not wait until the data is collected.
}
console.log(titles[0]);

This next code is from this post

console.log(get_title(video-id));
async function get_title(video-id) {
    // this also doesn't work. returns undefined.
    await getYoutubeTitle(video-id, api-key, (e, t) => {
        return this.title = t
    });
}

When using your own API key, it gets the titles accurately. What I've learned when researching for this, is that Node.js is asynchronous (this is my first node.js project, don't judge me), so it kind of makes sense.

I've tried a couple more packages, but those also failed.

ytdl-core from this post

a fork of the original get-youtube-title npm-package, get-youtube-title-await

always using this setup:

const titles = [];
// geting title with some npm-package and pushing data in titles;
console.log(titles[0]); // undefined

jQuery

That is when I've switched to the client. I am using socket.io, and I've found out that this is also async both on client and server.
I've tried this answer on stackoverflow, and same issue.

Even though Javascript should be single-threaded, so it should wait, right?

I am using google's cdn.

I don't really want to use jQuery, but if only this version works, jQuery answers are appreciated.

Conclusion

Console.log()-ing always works! It always waits until the data is collected!

I just want to change a div's innerText, and it returns undefined.


问:
Compare 2 Multidimensional Arrays in PHP and show all the difference in an array
I have 2 Multiple-Arrays and I want to compare them. In the second Array I want then show with colors which value has changed, which key is new and which key is removed.

I have found a lot of different solutions, but no one function for me.

Here are my arrays:

{
    "originFormation": {
        "stationName": "Bern",
        "sections": [{
            "name": "B",
            "cars": [{
                "type": "LOK",
                "occupancy": "UNKNOWN",
                "attributes": [],
                "closed": false,
                "previousPassage": false,
                "nextPassage": false
            }]
        }, {
            "name": "C",
            "cars": [{
                "type": "CAR",
                "number": "1",
                "class": "1",
                "occupancy": "UNKNOWN",
                "attributes": ["AbteilRollstuhl", "AbteilBusiness"],
                "closed": false,
                "previousPassage": false,
                "nextPassage": true
            }, {
                "type": "CAR",
                "number": "1",
                "class": "2",
                "occupancy": "UNKNOWN",
                "attributes": [],
                "closed": false,
                "previousPassage": true,
                "nextPassage": true
            }]
        }],
        "legendItems": [{
                "id": "1",
                "text": "1st class coach",
                "refersTo": "type"
            }, {
                "id": "2",
                "text": "2st class coach",
                "refersTo": "type"
            }, {
                "id": "Fahrtrichtung",
                "text": "Direction of travel",
                "refersTo": "code"
            }, {
                "id": "FA",
                "text": "Family Coach with play area",
                "refersTo": "type"
            }, {
                "id": "AbteilRollstuhl",
                "text": "Wheelchair space",
                "refersTo": "code"
            }, {
                "id": "AbteilVeloPl",
                "text": "Bicycle loading: Without reservation",
                "refersTo": "code"
            }, {
                "id": "LK",
                "text": "Locomotive",
                "refersTo": "type"
            }, {
                "id": "WR",
                "text": "Restaurant 1st and 2nd class",
                "refersTo": "type"
            }, {
                "id": "AbteilBusiness",
                "text": "Business zone in 1st class: Reservation possible",
                "refersTo": "code"
            },
            {
                "id": "HFS_WG_NUM",
                "text": "Coach",
                "refersTo": "code"
            }, {
                "id": "KD",
                "text": "No passage",
                "refersTo": "type"
            }
        ],
        "info": {
            "title": "Changes to the composition of the train",
            "formationChanges": []
        }
    }
}
```
<p><strong>Array2:</strong></p>
```{
"originFormation": {
    "stationName": "Bern",
    "sections": [
        {
            "name": "B",
            "cars": [
                {
                    "type": "LOK",
                    "occupancy": "UNKNOWN",
                    "attributes": [],
                    "closed": false,
                    "previousPassage": false,
                    "nextPassage": false
                }
            ]
        },
        {
            "name": "C",
            "cars": [
                {
                    "type": "CAR",
                    "number": "12",
                    "class": "1",
                    "occupancy": "UNKNOWN",
                    "attributes": [
                        "AbteilRollstuhl",
                        "AbteilBusiness"
                    ],
                    "closed": false,
                    "previousPassage": false,
                    "nextPassage": true
                },
                {
                    "type": "CAR",
                    "number": "1",
                    "class": "2",
                    "occupancy": "UNKNOWN",
                    "attributes": [
                                                "AbteilStefan"
                                            ],
                    "closed": false,
                    "previousPassage": true,
                    "nextPassage": true
                },
                {
                    "type": "CAR",
                    "number": "2",
                    "class": "1",
                    "occupancy": "UNKNOWN",
                    "attributes": [],
                    "closed": false,
                    "previousPassage": true,
                    "nextPassage": true
                }
            ]
        }
    ],
    "legendItems": [
        {
            "id": "1",
            "text": "1st class coach",
            "refersTo": "type"
        },
        {
            "id": "2",
            "text": "2st class coach",
            "refersTo": "type"
        },
        {
            "id": "Fahrtrichtung",
            "text": "Direction of travel",
            "refersTo": "code"
        },
        {
            "id": "FA",
            "text": "Family Coach with play area",
            "refersTo": "type"
        },
        {
            "id": "AbteilRollstuhl",
            "text": "Wheelchair space",
            "refersTo": "code"
        },
        {
            "id": "AbteilVeloPl",
            "text": "Bicycle loading: Without reservation",
            "refersTo": "code"
        },
        {
            "id": "LK",
            "text": "Locomotive",
            "refersTo": "type"
        },
        {
            "id": "WR",
            "text": "Restaurant 1st and 2nd class",
            "refersTo": "type"
        },
        {
            "id": "AbteilBusiness",
            "text": "Business zone in 1st class: Reservation possible",
            "refersTo": "code"
        },
        {
            "id": "AbteilStefan",
            "text": "Ich bin ein neues Abteil",
            "refersTo": "code"
        },
        {
            "id": "HFS_WG_NUM",
            "text": "Coach",
            "refersTo": "code"
        },
        {
            "id": "KD",
            "text": "No passage",
            "refersTo": "type"
        }
    ],
    "info": {
        "title": "Changes to the composition of the train",
        "formationChanges": [
            "All Changed"
        ]
    }
}
}
```
<p>My fonction to compare:</p>
```function array_diff_assoc_recursive($array1, $array2)
{
foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
            if(!isset($array2[$key]))
            {
                $difference[$key] = $value;
            }
            elseif(!is_array($array2[$key]))
            {
                $difference[$key] = "".$value."";
            }
            else
            {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if($new_diff != FALSE)
                {
                    $difference[$key] = $new_diff;
                }
            }
        }
        elseif(!isset($array2[$key]) || $array2[$key] != $value)
        {
            $difference[$key] = "".$value."";
        }
    }
    return !isset($difference) ? 0 : $difference;
}

var_dump(array_diff_assoc_recursive($array2, $array1));
```
<p><strong>This difference i get:</strong></p>
```[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1][attributes] -> newValue AbteilStefan
[originformation][sections][1][cars][2] -> all Attributes are new
[originformation][legendItems][9][id] -> newValue AbteilStefan
[originformation][legendItems][9][text] -> newValue Ich bin ein neues Abteil
[originformation][legendItems][10] -> all Attributes are new
[originformation][legendItems][11] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed
```
<p><strong>The difference i expected</strong></p>
```[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1] -> all Attributes are new
[originformation][legendItems][9] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed
```

Problem

My function doesn't see, that car in Array2 I put in a complete new car and also a complete new legendItem and the rest is still the same.

Does someone know how I can compare the arrays, that he doesn't check the order of the attributes on the same level?

Body:
I have 2 Multiple-Arrays and I want to compare them. In the second Array I want then show with colors which value has changed, which key is new and which key is removed.

I have found a lot of different solutions, but no one function for me.

Here are my arrays:

{
    "originFormation": {
        "stationName": "Bern",
        "sections": [{
            "name": "B",
            "cars": [{
                "type": "LOK",
                "occupancy": "UNKNOWN",
                "attributes": [],
                "closed": false,
                "previousPassage": false,
                "nextPassage": false
            }]
        }, {
            "name": "C",
            "cars": [{
                "type": "CAR",
                "number": "1",
                "class": "1",
                "occupancy": "UNKNOWN",
                "attributes": ["AbteilRollstuhl", "AbteilBusiness"],
                "closed": false,
                "previousPassage": false,
                "nextPassage": true
            }, {
                "type": "CAR",
                "number": "1",
                "class": "2",
                "occupancy": "UNKNOWN",
                "attributes": [],
                "closed": false,
                "previousPassage": true,
                "nextPassage": true
            }]
        }],
        "legendItems": [{
                "id": "1",
                "text": "1st class coach",
                "refersTo": "type"
            }, {
                "id": "2",
                "text": "2st class coach",
                "refersTo": "type"
            }, {
                "id": "Fahrtrichtung",
                "text": "Direction of travel",
                "refersTo": "code"
            }, {
                "id": "FA",
                "text": "Family Coach with play area",
                "refersTo": "type"
            }, {
                "id": "AbteilRollstuhl",
                "text": "Wheelchair space",
                "refersTo": "code"
            }, {
                "id": "AbteilVeloPl",
                "text": "Bicycle loading: Without reservation",
                "refersTo": "code"
            }, {
                "id": "LK",
                "text": "Locomotive",
                "refersTo": "type"
            }, {
                "id": "WR",
                "text": "Restaurant 1st and 2nd class",
                "refersTo": "type"
            }, {
                "id": "AbteilBusiness",
                "text": "Business zone in 1st class: Reservation possible",
                "refersTo": "code"
            },
            {
                "id": "HFS_WG_NUM",
                "text": "Coach",
                "refersTo": "code"
            }, {
                "id": "KD",
                "text": "No passage",
                "refersTo": "type"
            }
        ],
        "info": {
            "title": "Changes to the composition of the train",
            "formationChanges": []
        }
    }
}

Array2:

{
"originFormation": {
    "stationName": "Bern",
    "sections": [
        {
            "name": "B",
            "cars": [
                {
                    "type": "LOK",
                    "occupancy": "UNKNOWN",
                    "attributes": [],
                    "closed": false,
                    "previousPassage": false,
                    "nextPassage": false
                }
            ]
        },
        {
            "name": "C",
            "cars": [
                {
                    "type": "CAR",
                    "number": "12",
                    "class": "1",
                    "occupancy": "UNKNOWN",
                    "attributes": [
                        "AbteilRollstuhl",
                        "AbteilBusiness"
                    ],
                    "closed": false,
                    "previousPassage": false,
                    "nextPassage": true
                },
                {
                    "type": "CAR",
                    "number": "1",
                    "class": "2",
                    "occupancy": "UNKNOWN",
                    "attributes": [
                                                "AbteilStefan"
                                            ],
                    "closed": false,
                    "previousPassage": true,
                    "nextPassage": true
                },
                {
                    "type": "CAR",
                    "number": "2",
                    "class": "1",
                    "occupancy": "UNKNOWN",
                    "attributes": [],
                    "closed": false,
                    "previousPassage": true,
                    "nextPassage": true
                }
            ]
        }
    ],
    "legendItems": [
        {
            "id": "1",
            "text": "1st class coach",
            "refersTo": "type"
        },
        {
            "id": "2",
            "text": "2st class coach",
            "refersTo": "type"
        },
        {
            "id": "Fahrtrichtung",
            "text": "Direction of travel",
            "refersTo": "code"
        },
        {
            "id": "FA",
            "text": "Family Coach with play area",
            "refersTo": "type"
        },
        {
            "id": "AbteilRollstuhl",
            "text": "Wheelchair space",
            "refersTo": "code"
        },
        {
            "id": "AbteilVeloPl",
            "text": "Bicycle loading: Without reservation",
            "refersTo": "code"
        },
        {
            "id": "LK",
            "text": "Locomotive",
            "refersTo": "type"
        },
        {
            "id": "WR",
            "text": "Restaurant 1st and 2nd class",
            "refersTo": "type"
        },
        {
            "id": "AbteilBusiness",
            "text": "Business zone in 1st class: Reservation possible",
            "refersTo": "code"
        },
        {
            "id": "AbteilStefan",
            "text": "Ich bin ein neues Abteil",
            "refersTo": "code"
        },
        {
            "id": "HFS_WG_NUM",
            "text": "Coach",
            "refersTo": "code"
        },
        {
            "id": "KD",
            "text": "No passage",
            "refersTo": "type"
        }
    ],
    "info": {
        "title": "Changes to the composition of the train",
        "formationChanges": [
            "All Changed"
        ]
    }
}
}

My fonction to compare:

function array_diff_assoc_recursive($array1, $array2)
{
foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
            if(!isset($array2[$key]))
            {
                $difference[$key] = $value;
            }
            elseif(!is_array($array2[$key]))
            {
                $difference[$key] = "".$value."";
            }
            else
            {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if($new_diff != FALSE)
                {
                    $difference[$key] = $new_diff;
                }
            }
        }
        elseif(!isset($array2[$key]) || $array2[$key] != $value)
        {
            $difference[$key] = "".$value."";
        }
    }
    return !isset($difference) ? 0 : $difference;
}

var_dump(array_diff_assoc_recursive($array2, $array1));

This difference i get:

[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1][attributes] -> newValue AbteilStefan
[originformation][sections][1][cars][2] -> all Attributes are new
[originformation][legendItems][9][id] -> newValue AbteilStefan
[originformation][legendItems][9][text] -> newValue Ich bin ein neues Abteil
[originformation][legendItems][10] -> all Attributes are new
[originformation][legendItems][11] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed

The difference i expected

[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1] -> all Attributes are new
[originformation][legendItems][9] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed

Problem

My function doesn't see, that car in Array2 I put in a complete new car and also a complete new legendItem and the rest is still the same.

Does someone know how I can compare the arrays, that he doesn't check the order of the attributes on the same level?


问:
Error happened after upgrading from angular 12 to 15.0.4 it happens when I run i18n script for translation
Error happened after upgrading from angular 12 to 15.0.4 it happens when I run i18n script for translation
"i18n:extract": "npm run i18n:extract-template && npm run i18n:extract-code && npm run i18n:merge"

and here is the rest of the commands

"i18n:extract-template": "ng extract-i18n projectname --format xlf --output-path src/i18n"

"i18n:extract-code": "ts-extract --include=src/**/*.ts --format=xlf --out-file=src/i18n/messages.xlf"

"i18n:merge": "ng run projectname:xliffmerge"

```<code>> ng run projectname:xliffmerge

An unhandled exception occurred: NOT SUPPORTED: keyword "id", use "$id" for schema ID
See "C:\Users\myuser\AppData\Local\Temp\ng-0IjTV1\angular-errors.log" for further details.
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file C:\WINDOWS\system32\cmd.exe
npm ERR! errno ENOENT
npm ERR! projectname@0.0.0 i18n:merge: `ng run projectname: xliffmerge`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the projectname@0.0.0 i18n:merge script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\myuser\AppData\Local\npm-cache\_logs\2022-12-22T16_10_23_311Z-debug.log
PS F:\projectnamefrontend\projectname>
</code>```

Body:
Error happened after upgrading from angular 12 to 15.0.4 it happens when I run i18n script for translation
"i18n:extract": "npm run i18n:extract-template && npm run i18n:extract-code && npm run i18n:merge"

and here is the rest of the commands

"i18n:extract-template": "ng extract-i18n projectname --format xlf --output-path src/i18n"

"i18n:extract-code": "ts-extract --include=src/**/*.ts --format=xlf --out-file=src/i18n/messages.xlf"

"i18n:merge": "ng run projectname:xliffmerge"

> ng run projectname:xliffmerge

An unhandled exception occurred: NOT SUPPORTED: keyword "id", use "$id" for schema ID
See "C:\Users\myuser\AppData\Local\Temp\ng-0IjTV1\angular-errors.log" for further details.
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file C:\WINDOWS\system32\cmd.exe
npm ERR! errno ENOENT
npm ERR! projectname@0.0.0 i18n:merge: `ng run projectname: xliffmerge`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the projectname@0.0.0 i18n:merge script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\myuser\AppData\Local\npm-cache\_logs\2022-12-22T16_10_23_311Z-debug.log
PS F:\projectnamefrontend\projectname>


问:
Fetch email using JavaxMail and Proxies
I'm trying to connect to a mail server using IMAP protocol and proxies with the JavaxMail library. Yet they seem not to work.

```<code>Properties properties = new Properties();
List<Message> messages = new ArrayList<>();
Host host = Host.getHostByMail(mail);

properties.put("proxySet", "true");
properties.put("mail.imap.proxy.host", "proxy host");
properties.put("mail.imap.proxy.port", "proxy port");
properties.put("mail.imap.proxy.user", "proxy user");
properties.put("mail.imap.proxy.password", "proxy passwd");

properties.put("mail.imap.host", host.toString());
properties.put("mail.imap.port", "143");
properties.put("mail.imap.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imap");
store.connect(host.toString(), mail, passwd);
Folder readOnly = store.getFolder("INBOX");
readOnly.open(Folder.READ_ONLY);
FlagTerm unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
</code>```

When I try to use this code it gives me this error:

```<code>Exception in thread "Timer-2" com.sun.mail.util.MailConnectException: Couldn't connect to
host, port: imap.tiscali.it, 143; timeout -1; Using web proxy host, port: proxy_host, proxy_port; nested exception is:
java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at mail.MailHandler.readMail(MailHandler.java:97)
at mail.MailHandler.readAllMail(MailHandler.java:143)
at mail.MailSender.onCall(MailSender.java:27)
at commands.Temp$1.run(Temp.java:21)
at java.base/java.util.TimerThread.mainLoop(Timer.java:566)
at java.base/java.util.TimerThread.run(Timer.java:516)
Caused by: java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.util.SocketFetcher.proxyConnect(SocketFetcher.java:877)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 8 more
</code>```

This happens when I use HTTP/HTTPS proxies, but when I use SOCKS proxies it gives

```<code>Connection dropped by server?
</code>```

Title: Fetch email using JavaxMail and Proxies

Body:
I'm trying to connect to a mail server using IMAP protocol and proxies with the JavaxMail library. Yet they seem not to work.

Properties properties = new Properties();
List<Message> messages = new ArrayList<>();
Host host = Host.getHostByMail(mail);

properties.put("proxySet", "true");
properties.put("mail.imap.proxy.host", "proxy host");
properties.put("mail.imap.proxy.port", "proxy port");
properties.put("mail.imap.proxy.user", "proxy user");
properties.put("mail.imap.proxy.password", "proxy passwd");

properties.put("mail.imap.host", host.toString());
properties.put("mail.imap.port", "143");
properties.put("mail.imap.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imap");
store.connect(host.toString(), mail, passwd);
Folder readOnly = store.getFolder("INBOX");
readOnly.open(Folder.READ_ONLY);
FlagTerm unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

When I try to use this code it gives me this error:

Exception in thread "Timer-2" com.sun.mail.util.MailConnectException: Couldn't connect to
host, port: imap.tiscali.it, 143; timeout -1; Using web proxy host, port: proxy_host, proxy_port; nested exception is:
java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at mail.MailHandler.readMail(MailHandler.java:97)
at mail.MailHandler.readAllMail(MailHandler.java:143)
at mail.MailSender.onCall(MailSender.java:27)
at commands.Temp$1.run(Temp.java:21)
at java.base/java.util.TimerThread.mainLoop(Timer.java:566)
at java.base/java.util.TimerThread.run(Timer.java:516)
Caused by: java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.util.SocketFetcher.proxyConnect(SocketFetcher.java:877)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 8 more

This happens when I use HTTP/HTTPS proxies, but when I use SOCKS proxies it gives

Connection dropped by server?


问:
Not able to take screenshot of alert box in selenium using python
i want to take the screenshot of alert box whenever the alert is popped. The code i have written is as below:

```<code>def test_js_alert_accept(self):
    self.driver.find_element(*self.JS_ALERT).click()
    js_alert = self.driver.switch_to.alert
    self.driver.get_screenshot_as_file('screenshot.png')
    js_alert.accept()

</code>```

I am facing the issue while taking the screenshot.The Error message is as below

```<code>raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
E           selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: None
E           Message: Dismissed user prompt dialog: I am a JavaScript Alert
</code>```

Body:
i want to take the screenshot of alert box whenever the alert is popped. The code i have written is as below:

def test_js_alert_accept(self):
    self.driver.find_element(*self.JS_ALERT).click()
    js_alert = self.driver.switch_to.alert
    self.driver.get_screenshot_as_file('screenshot.png')
    js_alert.accept()

I am facing the issue while taking the screenshot.The Error message is as below

raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
E           selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: None
E           Message: Dismissed user prompt dialog: I am a JavaScript Alert


问:
jdbc query using select with all column title instead of using '*' in oracle table join
I'm trying to use join method with two table; one is Pokemon and another one is Trainer.

I made xml file related to Oracle and working in JDBC environment
It was successfully working to see the result in console if I used the quote in xml file:

```<code>SELECT
*
FROM   POKEMON p
     , TRAINER t
WHERE p.TRNO = t.TRNO
AND t.TRID = ?
</code>```

but how i wanted to write instead of * in xml is:

```<code>SELECT  PKNO
              , p.PKNAME
              , p.PKTYPE
              , p.PKCLASS
              , p.PKHEIGHT
              , p.PKWEIGHT
              , p.PKDETAIL
              , t.TRNO (or p.TRNO since TRNO in POKEMON is referenced to TRNO in TRAINER table)
FROM POKEMON p, TRAINER t
WHERE p.TRNO = t.TRNO
AND t.TRID = 'user01';
</code>```

Above those two quote without '*' are working finely in Oracle Developer but I want them to be used in xml file and i want to see them working in Eclipse.

Unfortunately the exception has been shown too and the result is not in English but I'm sure it must be 'Ambiguous Name Column' something like this in English. I don't know why it is not shown in English even though I'm using Eclipse in English. Please let me know if there's any information I should add for your convenience since I'm not still familir with SOF. Thank you!!

Code for the query :

```<code>public ArrayList<Pokemon> displayMyPokemon(Connection conn, String userId) {
        ArrayList<Pokemon> list = new ArrayList<Pokemon>();
        PreparedStatement pstmt = null;
        ResultSet rset = null;
        String sql = prop.getProperty("displayMyPokemon");

        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            rset = pstmt.executeQuery();

            while (rset.next()) {

                Trainer t = new Trainer();
                t.setTrNo(rset.getInt("TRNO"));
                t.setTrId(rset.getString("TRID"));
                t.setTrPwd(rset.getString("TRPWD"));
                t.setTrName(rset.getString("TRNAME"));

                Pokemon p = new Pokemon(rset.getInt("PKNO"), rset.getString("PKNAME"), rset.getString("PKTYPE"),
                        rset.getString("PKCLASS"), rset.getDouble("PKHEIGHT"), rset.getDouble("PKWEIGHT"),
                        rset.getString("PKDETAIL"), rset.getInt("TRNO"));

                list.add(p);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rset);
            close(pstmt);

        }

        return list;
    }

</code>```

Table Pokemon

```<code>PKNO    NUMBER  No
PKNAME  VARCHAR2(30 BYTE)   No
PKTYPE  VARCHAR2(30 BYTE)   No
PKCLASS VARCHAR2(30 BYTE)   No
PKHEIGHT    NUMBER  Yes
PKWEIGHT    NUMBER  Yes
PKDETAIL    VARCHAR2(200 BYTE)  Yes
TRNO    NUMBER  Yes
</code>```

Table Trainer

```<code>TRNO    NUMBER  Yes
TRID    VARCHAR2(30 BYTE)   No
TRPWD   VARCHAR2(30 BYTE)   No
TRNAME  VARCHAR2(30 BYTE)   No
</code>```

TRNO in Pokemon is references the one in Trainer

Body:
I'm trying to use join method with two table; one is Pokemon and another one is Trainer.

I made xml file related to Oracle and working in JDBC environment
It was successfully working to see the result in console if I used the quote in xml file:

SELECT
*
FROM   POKEMON p
     , TRAINER t
WHERE p.TRNO = t.TRNO
AND t.TRID = ?

but how i wanted to write instead of * in xml is:

SELECT  PKNO
              , p.PKNAME
              , p.PKTYPE
              , p.PKCLASS
              , p.PKHEIGHT
              , p.PKWEIGHT
              , p.PKDETAIL
              , t.TRNO (or p.TRNO since TRNO in POKEMON is referenced to TRNO in TRAINER table)
FROM POKEMON p, TRAINER t
WHERE p.TRNO = t.TRNO
AND t.TRID = 'user01';

Above those two quote without '*' are working finely in Oracle Developer but I want them to be used in xml file and i want to see them working in Eclipse.

Unfortunately the exception has been shown too and the result is not in English but I'm sure it must be 'Ambiguous Name Column' something like this in English. I don't know why it is not shown in English even though I'm using Eclipse in English. Please let me know if there's any information I should add for your convenience since I'm not still familir with SOF. Thank you!!

Code for the query :

public ArrayList<Pokemon> displayMyPokemon(Connection conn, String userId) {
        ArrayList<Pokemon> list = new ArrayList<Pokemon>();
        PreparedStatement pstmt = null;
        ResultSet rset = null;
        String sql = prop.getProperty("displayMyPokemon");

        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            rset = pstmt.executeQuery();

            while (rset.next()) {

                Trainer t = new Trainer();
                t.setTrNo(rset.getInt("TRNO"));
                t.setTrId(rset.getString("TRID"));
                t.setTrPwd(rset.getString("TRPWD"));
                t.setTrName(rset.getString("TRNAME"));

                Pokemon p = new Pokemon(rset.getInt("PKNO"), rset.getString("PKNAME"), rset.getString("PKTYPE"),
                        rset.getString("PKCLASS"), rset.getDouble("PKHEIGHT"), rset.getDouble("PKWEIGHT"),
                        rset.getString("PKDETAIL"), rset.getInt("TRNO"));

                list.add(p);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rset);
            close(pstmt);

        }

        return list;
    }

Table Pokemon

PKNO    NUMBER  No
PKNAME  VARCHAR2(30 BYTE)   No
PKTYPE  VARCHAR2(30 BYTE)   No
PKCLASS VARCHAR2(30 BYTE)   No
PKHEIGHT    NUMBER  Yes
PKWEIGHT    NUMBER  Yes
PKDETAIL    VARCHAR2(200 BYTE)  Yes
TRNO    NUMBER  Yes

Table Trainer

TRNO    NUMBER  Yes
TRID    VARCHAR2(30 BYTE)   No
TRPWD   VARCHAR2(30 BYTE)   No
TRNAME  VARCHAR2(30 BYTE)   No

TRNO in Pokemon is references the one in Trainer


问:
Core Data: Not fetching entity (one to many relationship)
I am new to Core Data and am using a one-to-many relationship for a simple Notes app. A folder can have "many" notes. When a folder is created, notes can be created in that folder. My problem is that when I press the icon that's supposed to add a note, it does nothing. It used to add a note but ever since I attempted a one-to-many relationship amongst folders and notes, it does nothing. I know I must have a logic error somewhere.

To "filter" the notes by folder I passed in an ObservedObject in the Note view (which is the subview of the Folder view). I tried to set up a notes array but I've had no luck. I feel like there's a problem with my Core Dara Properties

FolderView:

```<code>struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {

        Button(){
            isPresented = true
        } label: {
            HStack{
                Image(systemName: "folder.badge.plus")
                Text("Add Folder")

            }
            .cornerRadius(50)

        }
        .sheet(isPresented: $isPresented){
            AddFolderView{ name in
                saveNewFolder(name: name)
            }
        }
            .padding()
        Divider()
        Text("Folders")
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(.caption)
            .foregroundColor(.secondary)
        List(folders, selection: $selectedFoldersIds){folder in
               HStack{
                        Image(systemName: "folder")
                   NavigationLink(folder.folderName!, destination:NoteView(rootFolder: folder))
                }

       }

        .onDeleteCommand(perform: deleteSelectedFolders)
        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: toggleSidebar) {
                    Image(systemName: "sidebar.left")
                }
            }
            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedFolders){
                    Label("Delete note", systemImage: "trash")
                }
            }
        }

}

    private func toggleSidebar() {
        NSApp.keyWindow?.firstResponder?
            .tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
    }

    func saveNewFolder(name: String){
           let folder = Folder(context: viewContext)
           folder.folderId = UUID()
           folder.folderName = name
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedFolders(){
        withAnimation{
            let selectedFolders = folders.filter {selectedFoldersIds.contains($0.id)}
            deleteFolders(folders: selectedFolders)
        }

    }

    private func deleteFolders(folders: [Folder]){
        viewContext.perform{ folders.forEach(viewContext.delete)}
    }
}

</code>```

Note view:

```<code>struct NoteView: View {
    @ObservedObject var rootFolder: Folder
    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List(rootFolder.notesArray, selection: $selectedNotesIds){ note in // is the problem here?
                    VStack{
                        NavigationLink(note.name!, destination: NoteEditor(note: note))
                        HStack{

                            Image(systemName: "folder")
                            Text(rootFolder.folderName!)
                        }
                        Divider()
                    }
               }

        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(){
                    isPresented.toggle()
                } label: {
                    Image(systemName: "square.and.pencil")
                }
                .sheet(isPresented: $isPresented){
                    AddNoteView{ name in
                        saveNewNote(name: name, text: "")
                    }
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedNotes){
                    Label("Delete note", systemImage: "trash")
                }
            }

        }

    }

    func saveNewNote(name: String, text: String){
           let note = Note(context: viewContext)
           note.id = UUID()
           note.name = name
           note.text = text
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedNotes(){
        withAnimation{
            let selectedNotes = notes.filter {selectedNotesIds.contains($0.id)}
            deleteNotes(notes: selectedNotes)
        }

    }

    private func deleteNotes(notes: [Note]){
        viewContext.perform{ notes.forEach(viewContext.delete)}
    }
}
</code>```

My Folder+CoreDataProperties:

```<code>extension Folder {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Folder> {
        return NSFetchRequest<Folder>(entityName: "Folder")
    }
    @nonobjc  class func fetchRequest(forID folderId: UUID) -> NSFetchRequest<Folder> {
            let request = Folder.fetchRequest()
            request.predicate = NSPredicate(format: "id = %@", folderId as CVarArg)
            return request
    }

    @NSManaged public var folderId: UUID?
    @NSManaged public var folderName: String?
    @NSManaged public var notes: NSSet?

    public var notesArray: [Note] {
            let set = notes as? Set<Note> ?? []
            return set.sorted {
                $0.wrappedName > $1.wrappedName
            }
        }

}

</code>```

Notes+CoreDataProperties:

```<code>extension Note {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
        return NSFetchRequest<Note>(entityName: "Note")
    }

    @nonobjc  class func fetchRequest(forID id: UUID) -> NSFetchRequest<Note> {
            let request = Note.fetchRequest()
            request.predicate = NSPredicate(format: "id = %@", id as CVarArg)
            return request
        }

    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var text: String?
    @NSManaged public var folder: Folder?

    public var wrappedName: String {
        name ?? "folderName"
    }

}
</code>```

Body:
I am new to Core Data and am using a one-to-many relationship for a simple Notes app. A folder can have "many" notes. When a folder is created, notes can be created in that folder. My problem is that when I press the icon that's supposed to add a note, it does nothing. It used to add a note but ever since I attempted a one-to-many relationship amongst folders and notes, it does nothing. I know I must have a logic error somewhere.

To "filter" the notes by folder I passed in an ObservedObject in the Note view (which is the subview of the Folder view). I tried to set up a notes array but I've had no luck. I feel like there's a problem with my Core Dara Properties

FolderView:

struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {

        Button(){
            isPresented = true
        } label: {
            HStack{
                Image(systemName: "folder.badge.plus")
                Text("Add Folder")

            }
            .cornerRadius(50)

        }
        .sheet(isPresented: $isPresented){
            AddFolderView{ name in
                saveNewFolder(name: name)
            }
        }
            .padding()
        Divider()
        Text("Folders")
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(.caption)
            .foregroundColor(.secondary)
        List(folders, selection: $selectedFoldersIds){folder in
               HStack{
                        Image(systemName: "folder")
                   NavigationLink(folder.folderName!, destination:NoteView(rootFolder: folder))
                }

       }

        .onDeleteCommand(perform: deleteSelectedFolders)
        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: toggleSidebar) {
                    Image(systemName: "sidebar.left")
                }
            }
            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedFolders){
                    Label("Delete note", systemImage: "trash")
                }
            }
        }

}

    private func toggleSidebar() {
        NSApp.keyWindow?.firstResponder?
            .tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
    }

    func saveNewFolder(name: String){
           let folder = Folder(context: viewContext)
           folder.folderId = UUID()
           folder.folderName = name
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedFolders(){
        withAnimation{
            let selectedFolders = folders.filter {selectedFoldersIds.contains($0.id)}
            deleteFolders(folders: selectedFolders)
        }

    }

    private func deleteFolders(folders: [Folder]){
        viewContext.perform{ folders.forEach(viewContext.delete)}
    }
}

Note view:

struct NoteView: View {
    @ObservedObject var rootFolder: Folder
    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List(rootFolder.notesArray, selection: $selectedNotesIds){ note in // is the problem here?
                    VStack{
                        NavigationLink(note.name!, destination: NoteEditor(note: note))
                        HStack{

                            Image(systemName: "folder")
                            Text(rootFolder.folderName!)
                        }
                        Divider()
                    }
               }

        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(){
                    isPresented.toggle()
                } label: {
                    Image(systemName: "square.and.pencil")
                }
                .sheet(isPresented: $isPresented){
                    AddNoteView{ name in
                        saveNewNote(name: name, text: "")
                    }
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedNotes){
                    Label("Delete note", systemImage: "trash")
                }
            }

        }

    }

    func saveNewNote(name: String, text: String){
           let note = Note(context: viewContext)
           note.id = UUID()
           note.name = name
           note.text = text
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedNotes(){
        withAnimation{
            let selectedNotes = notes.filter {selectedNotesIds.contains($0.id)}
            deleteNotes(notes: selectedNotes)
        }

    }

    private func deleteNotes(notes: [Note]){
        viewContext.perform{ notes.forEach(viewContext.delete)}
    }
}

My Folder+CoreDataProperties:

extension Folder {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Folder> {
        return NSFetchRequest<Folder>(entityName: "Folder")
    }
    @nonobjc  class func fetchRequest(forID folderId: UUID) -> NSFetchRequest<Folder> {
            let request = Folder.fetchRequest()
            request.predicate = NSPredicate(format: "id = %@", folderId as CVarArg)
            return request
    }

    @NSManaged public var folderId: UUID?
    @NSManaged public var folderName: String?
    @NSManaged public var notes: NSSet?

    public var notesArray: [Note] {
            let set = notes as? Set<Note> ?? []
            return set.sorted {
                $0.wrappedName > $1.wrappedName
            }
        }

}

Notes+CoreDataProperties:

extension Note {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
        return NSFetchRequest<Note>(entityName: "Note")
    }

    @nonobjc  class func fetchRequest(forID id: UUID) -> NSFetchRequest<Note> {
            let request = Note.fetchRequest()
            request.predicate = NSPredicate(format: "id = %@", id as CVarArg)
            return request
        }

    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var text: String?
    @NSManaged public var folder: Folder?

    public var wrappedName: String {
        name ?? "folderName"
    }

}


问:
MS Azure VM + Visual Studio + VS Code and with AWS
After a strong battle, I managed to set up MS Azure Account, set up Windows VM, install Chrome, install VS 2022, and VSCode. Also, I managed to connect from Desktop RDP and also from the Browser using the Bastion feature. This means I can now connect to the Azure VM using the Browser and no need for an RDP Desktop client. All such features are free based on a credit I got which will end after I utilize the remaining balance. I am also trying to have the same setup using AWS, but still struggling.

I thought this approach will allow me to connect to my local dev environment and no need to worry about updating my laptop to work with such technologies.

Now I can work on my Java and C# Projects from the Library Desktop computers and no need to carry my laptop with me, or this is what I am hoping at least. I realized after many years of working with different laptops, I have to upgrade it one day, and maintaining my laptop is very cumbersome.

I am wondering if anyone has been through such a setup and if it is worth it, and if you recommend using AWS or MS Azure. And, probably paying for the cloud subscription fee is more cost-effective compared to the cost of updating and maintaining your laptop.

I appreciate your feedback.


问:
Python Calculating Standard Deviation using SQLLite db data with statistics library
I am able to get data of the column I want but I cant use its data, because it is in tuple form, to calculate its standard deviation. I get following errors.

```<code>cursor.execute("select SMA from PRICES")
smaColum = cursor.fetchall()
std = statistics.stdev(smaColum)
</code>```

return (x.numerator, x.denominator)

AttributeError: 'tuple' object has no attribute 'numerator'

TypeError: can't convert type 'tuple' to numerator/denominator

Body:
I am able to get data of the column I want but I cant use its data, because it is in tuple form, to calculate its standard deviation. I get following errors.

cursor.execute("select SMA from PRICES")
smaColum = cursor.fetchall()
std = statistics.stdev(smaColum)

return (x.numerator, x.denominator)

AttributeError: 'tuple' object has no attribute 'numerator'

TypeError: can't convert type 'tuple' to numerator/denominator


问:
Clipped print output from CUPS / HPLJ5m
When printing through the CUPS API, everything looks excellent when output to PDF and view the result in Firefox. But when printing to a real printer, HPLJ5m, the printing area gets clipped. I print on A4 paper and tries to configure that with options when creating the print job.
The height of the printed area corresponds to the size of US letter, coincidal or not? The position is nicely aligned. Without this masking everything would have been perfect. The print data is a PDF with just image data.
Maybe the option sent to cupsCreateDestJob() does not override all the rubbish in the .ppd-file for my printer? Can that, if necceccary, be done through the API?

```<code>  options=NULL; num_options=0;
  num_options = D_cupsAddOption(CUPS_COPIES, "1", num_options, &options);
  num_options = D_cupsAddOption(CUPS_MEDIA, CUPS_MEDIA_A4, num_options, &options);
  num_options = D_cupsAddOption(CUPS_SIDES, CUPS_SIDES_ONE_SIDED, num_options, &options);

  info = D_cupsCopyDestInfo(CUPS_HTTP_DEFAULT, printer);

  if (D_cupsCreateDestJob(CUPS_HTTP_DEFAULT, printer, info,
                        &job_id, "tideq", num_options,
                        options) != IPP_STATUS_OK) goto failed;
</code>```

Here is the relevant part of the print data sent to cups. There are margins for the dead zones at the borders.

```<code>%PDF-1.7
%åäö

1 0 obj
  << /Type /Catalog
     /Pages 2 0 R
  >>
endobj

2 0 obj
  << /Type /Pages
     /Kids [3 0 R
            7 0 R
            ]
     /Count 2
     /MediaBox [0 0 595 842]
  >>
endobj

3 0 obj
  << /Type /Page
     /Parent 1 0 R
     /CropBox [0 0 595 842]
     /Resources 4 0 R
     /Contents 6 0 R
  >>
endobj

4 0 obj
  << /ProcSet [ /PDF /ImageB ]
     /XObject << /Im1 5 0 R >>
  >>
endobj

5 0 obj
  << /Type /XObject
     /Subtype /Image
     /Width 1281
     /Height 1500
     /ColorSpace /DeviceGray
     /BitsPerComponent 8
     /Length 3843001
     /Filter /ASCIIHexDecode
  >>
stream
<page data goes here>
endstream
endobj

6 0 obj
  << /Length 40 >>
stream
  q
  555 0 0 802 20 20 cm
  /Im1 Do
  Q
endstream
endobj
</code>```

Title: Clipped print output from CUPS / HPLJ5m

Body:
When printing through the CUPS API, everything looks excellent when output to PDF and view the result in Firefox. But when printing to a real printer, HPLJ5m, the printing area gets clipped. I print on A4 paper and tries to configure that with options when creating the print job.
The height of the printed area corresponds to the size of US letter, coincidal or not? The position is nicely aligned. Without this masking everything would have been perfect. The print data is a PDF with just image data.
Maybe the option sent to cupsCreateDestJob() does not override all the rubbish in the .ppd-file for my printer? Can that, if necceccary, be done through the API?

  options=NULL; num_options=0;
  num_options = D_cupsAddOption(CUPS_COPIES, "1", num_options, &options);
  num_options = D_cupsAddOption(CUPS_MEDIA, CUPS_MEDIA_A4, num_options, &options);
  num_options = D_cupsAddOption(CUPS_SIDES, CUPS_SIDES_ONE_SIDED, num_options, &options);

  info = D_cupsCopyDestInfo(CUPS_HTTP_DEFAULT, printer);

  if (D_cupsCreateDestJob(CUPS_HTTP_DEFAULT, printer, info,
                        &job_id, "tideq", num_options,
                        options) != IPP_STATUS_OK) goto failed;

Here is the relevant part of the print data sent to cups. There are margins for the dead zones at the borders.

%PDF-1.7
%åäö

1 0 obj
  << /Type /Catalog
     /Pages 2 0 R
  >>
endobj

2 0 obj
  << /Type /Pages
     /Kids [3 0 R
            7 0 R
            ]
     /Count 2
     /MediaBox [0 0 595 842]
  >>
endobj

3 0 obj
  << /Type /Page
     /Parent 1 0 R
     /CropBox [0 0 595 842]
     /Resources 4 0 R
     /Contents 6 0 R
  >>
endobj

4 0 obj
  << /ProcSet [ /PDF /ImageB ]
     /XObject << /Im1 5 0 R >>
  >>
endobj

5 0 obj
  << /Type /XObject
     /Subtype /Image
     /Width 1281
     /Height 1500
     /ColorSpace /DeviceGray
     /BitsPerComponent 8
     /Length 3843001
     /Filter /ASCIIHexDecode
  >>
stream
<page data goes here>
endstream
endobj

6 0 obj
  << /Length 40 >>
stream
  q
  555 0 0 802 20 20 cm
  /Im1 Do
  Q
endstream
endobj