text:
Q: The first batch data output of multilingual BERT is NAN the error
When I train the model with MBERT, my model always has NAN at the first batch.
My code :
# -*- encoding:utf-8 -*-
import torch
import torch.nn as nn
import transformers
from transformers import AutoModel, AutoTokenizer
from transformers import AdamW, get_linear_schedule_with_warmup
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from Data.Ner_data import Ner_Dataset
from utili.tools import envaulation, GradReverse
from torch.utils.data import DataLoader
from datasets import load_metric
import numpy as np
import random

class mBERT_DANN(pl.LightningModule):
    def __init__(self, args, lr, index_times, save_log_path):
        super().__init__()
        self.save_hyperparameters()
        self.bert = AutoModel.from_pretrained(args.model_path)
        self.tokenizer = AutoTokenizer.from_pretrained(args.model_path)
        self.CE_loss = nn.CrossEntropyLoss()
        self.index_times = index_times
        self.lr = lr
        self.args = args
        self.save_log_path = save_log_path
        self.metric = load_metric("seqeval")
        self.label_name = ['O', 'B-PER', 'I-PER', 'B-ORG', 'I-ORG', 'B-LOC', 'I-LOC', 'B-MISC', 'I-MISC']
        self.num_labels = 9 if self.args.data == 'conll' else 7
        self.data_loader_len = 100 if self.args.data == 'conll' else 150

        self.fc = nn.Sequential(
            nn.ReLU(),
            nn.Dropout(args.dropout),
            nn.Linear(self.bert.config.hidden_size, self.num_labels))

        self.domain_fc = nn.Sequential(
            nn.Linear(self.bert.config.hidden_size, args.hidden),
            nn.ReLU(),
            nn.Dropout(args.dropout),
            nn.Linear(args.hidden, args.class_num))

    def forward(self, inputs=None, is_train=True, alpha=1):
        # source 的进行分类, target 和source 进行对抗
        print(' the bert inputs============={}============='.format(inputs))
        bert_out = self.bert(**inputs)[0]
        print('==============the bert output ======== {}==================='.format(bert_out))
        logits = self.fc(bert_out)  # batch_size *  seq_length * num_lables

        if is_train:
            # ============== 对抗======================
            mean_last_hidden = torch.mean(bert_out, dim=1)
            reverse_feature = GradReverse.apply(mean_last_hidden, alpha)
            logits_dann = self.domain_fc(reverse_feature)
            return logits, logits_dann

        else:  # 验证在source , 测试在target

            return logits

    def training_step(self, batch, batch_idx):
        p = float(batch_idx + self.current_epoch * self.data_loader_len) / self.args.epochs / self.data_loader_len
        alpha = 2. / (1. + np.exp(-10 * p)) - 1

        batch_source = batch['source']
        batch_target = batch['target']

        # ====================================== source  =========================================
        source_bert_inputs = batch_source[0]
        source_real_labels = batch_source[1]
        source_label_mask = batch_source[2]

        cur_source_batch_size = source_real_labels.shape[0]
        # source 的domain 设置为0
        source_domain = torch.zeros(cur_source_batch_size, device=self.device, dtype=torch.long)
        # for one in source_bert_inputs['input_ids']:
        #     print(one)

        # self.print('++++++++++++++++{}++++++++++++++++++++'.format(source_bert_inputs))
        logits, logits_dann = self(inputs=source_bert_inputs, alpha=alpha, is_train=True)
        # Only keep active parts of the loss
        active_loss = source_label_mask.view(-1) == 1
        active_logits = logits.view(-1, self.num_labels)[active_loss]  # 预测的结果
        active_labels = source_real_labels.view(-1)[active_loss]  # 真实的结果
        loss_discri = self.CE_loss(active_logits, active_labels)

        source_loss_dann = self.CE_loss(logits_dann, source_domain)
        # ====================================== target =============================================
        target_bert_inputs = batch_target[0]
        target_real_labels = batch_target[1]

        cur_target_batch_size = target_real_labels.shape[0]
        # target 的domain 设置为1
        target_domain = torch.ones(cur_target_batch_size, device=self.device, dtype=torch.long)

        _, logits_dann = self(inputs=target_bert_inputs, alpha=alpha, is_train=True)

        target_loss_dann = self.CE_loss(logits_dann, target_domain)
        loss = loss_discri + source_loss_dann + target_loss_dann
        loss_metirc = {"loss_discri": loss_discri, "source_loss": source_loss_dann, "target_loss": target_loss_dann}

        self.log_dict(loss_metirc, prog_bar=True, logger=True, on_epoch=True)

        return {"loss": loss}

    def training_step_end(self, training_step_outputs):
        pass

    def training_epoch_end(self, training_step_outputs):
        pass

    def share_val_step(self, batch):
        bert_inputs = batch[0]
        real_labels = batch[1]

        logits = self(inputs=bert_inputs,  is_train=False)
        y_pred_label = logits.argmax(dim=-1)
        # result_dict = self.compute_metrics(labels=real_labels, predictions=y_pred_label)
        return real_labels, y_pred_label

    def validation_step(self, batch, batch_idx):
        real_lables, pred_labels = self.share_val_step(batch)
        return {'real_label': real_lables, 'pred_labels': pred_labels}

    def validation_step_end(self, val_step_outputs):
        pass

    def validation_epoch_end(self, validation_step_outputs):
        result_dict = self.shared_epoch_end(validation_step_outputs)
        metrics = {'val_f1': result_dict['f1']}
        self.log_dict(metrics, prog_bar=True, logger=True, on_epoch=True)

    def test_step(self, batch, batch_idx):
        real_lables, pred_labels = self.share_val_step(batch)
        return {'real_label': real_lables, 'pred_labels': pred_labels}

    def test_step_end(self, output_results):
        pass

    def test_epoch_end(self, test_step_outputs):
        result_dict = self.shared_epoch_end(test_step_outputs)
        metrics = {'test_f1': result_dict['f1']}
        self.log_dict(metrics, prog_bar=True, logger=True, on_epoch=True)

    def shared_epoch_end(self, outpts):
        real_label = torch.cat([x["real_label"] for x in outpts], dim=0)
        pre_label = torch.cat([x["pred_labels"] for x in outpts], dim=0)
        result_dict = self.compute_metrics(predictions=pre_label, labels=real_label)
        return result_dict

    def configure_optimizers(self):
        no_decay = ['bias', 'LayerNorm.weight']
        optimizer_grouped_parameters = [  # 将权重衰减应用于除了'偏移'这些之外的所有参数
            # n是模型每层名字,p是每层参数,model是模型名字
            {'params': [p for n, p in self.bert.named_parameters() if not any(nd in n for nd in no_decay)],
             'weight_decay': 0.001},
            {'params': [p for n, p in self.bert.named_parameters() if any(nd in n for nd in no_decay)],
             'weight_decay': 0.0}
        ]
        optimizer = AdamW(optimizer_grouped_parameters, lr=self.lr, weight_decay=self.args.weight_decay)
        scheduler = get_linear_schedule_with_warmup(optimizer,
                                                    num_warmup_steps=self.args.warmup_steps,
                                                    num_training_steps=self.args.total_steps)
        scheduler = {"scheduler": scheduler, "interval": "step", "frequency": 1}
        return [optimizer], [scheduler]

    def train_dataloader(self):
        # source
        source_train_data = Ner_Dataset(data=self.args.data, language=self.args.s, desc='train')
        # 把无效的数据过滤一下

        # target
        target_train_data = Ner_Dataset(data=self.args.data, language=self.args.t, desc='train')

        source_data_loader = DataLoader(source_train_data, batch_size=self.args.batch_size, shuffle=True,
                                        collate_fn=self.collate)

        target_data_loader = DataLoader(target_train_data, batch_size=self.args.batch_size, shuffle=True,
                                        collate_fn=self.collate)
        return {'source': source_data_loader, 'target': target_data_loader}

    def val_dataloader(self):
        # source
        val_data = Ner_Dataset(data=self.args.data, language=self.args.s, desc='valid')
        return DataLoader(val_data, batch_size=self.args.batch_size,
                          shuffle=False, collate_fn=self.collate)

    def test_dataloader(self):
        # target
        # conll   de es nl     wikiann  ar hi zh

        test_data = Ner_Dataset(data=self.args.data, language=self.args.t, desc='test')

        return DataLoader(test_data, batch_size=self.args.batch_size, shuffle=False, collate_fn=self.collate)

    def compute_metrics(self, predictions, labels):
        """
        :param predictions:  batch * seq
        :param labels:  batch *seq
        :return:
        """
        predictions = predictions.cpu().detach().numpy().tolist()
        labels = labels.cpu().detach().numpy().tolist()

        # 预测结果和真实标签
        # Remove ignored index (special tokens) and convert to labels
        # 把真实标签中label是-100的去掉
        true_labels = [[self.label_name[l] for l in label if l != -100] for label in labels]
        # 确保和label的长度一致,并且把-100的去掉
        true_predictions = [
            [self.label_name[p] for (p, l) in zip(prediction, label) if l != -100]
            for prediction, label in zip(predictions, labels)
        ]
        all_metrics = self.metric.compute(predictions=true_predictions, references=true_labels)
        return {
            "precision": all_metrics["overall_precision"],
            "recall": all_metrics["overall_recall"],
            "f1": all_metrics["overall_f1"],
            "accuracy": all_metrics["overall_accuracy"],
        }

    def align_labels_with_tokens(self, labels, word_ids):
        # word_ids=[None, 0, 1, 2, 3, 4, 5, 6, 7, 7, 8, None]
        # labels=[3, 0, 7, 0, 0, 0, 7, 0, 0]
        new_labels = []
        label_mask = []
        current_word = None
        for word_id in word_ids:
            if word_id != current_word:
                # Start of a new word!
                current_word = word_id
                label = -100 if word_id is None else labels[word_id]
                new_labels.append(label)
                # 不是None的位置才是需要的 标准为1
                label_mask.append(0 if label == -100 else 1)
            elif word_id is None:
                # Special token
                new_labels.append(-100)
                # 特殊字符都标注为0
                label_mask.append(0)
            else:
                # Same word as previous token
                # label = labels[word_id]
                # # If the label is B-XXX we change it to I-XXX
                # if label % 2 == 1:
                #     label += 1
                # new_labels.append(label)
                # 相同的单词只需要保留第一个位置的就行,其他的为None
                new_labels.append(-100)
                # sub-word的单词,除了第一个word, 其他的都标注为0
                label_mask.append(0)
        # 这里就是把token 切分为sub-word, 然后给每个sub-word 打上ner标签
        # [-100, 3, 0, 7, 0, 0, 0, 7, 0, 0, 0, -100]
        return new_labels, label_mask

    def collate(self, examples):
        all_tokens = [one['tokens'] for one in examples]
        all_labels = [one['ner_tags'] for one in examples]

        # 处理一个batch的数据
        tokenized_inputs = self.tokenizer(all_tokens, is_split_into_words=True, padding='max_length',
                                          max_length=self.args.max_length, truncation=True,
                                          return_tensors="pt",
                                          add_special_tokens=True
                                          )
        new_labels_list = []
        label_mask_list = []
        for i, labels in enumerate(all_labels):
            word_ids = tokenized_inputs.word_ids(i)
            new_labels, label_mask = self.align_labels_with_tokens(labels, word_ids)
            new_labels_list.append(new_labels)
            label_mask_list.append(label_mask)
        return tokenized_inputs, torch.tensor(new_labels_list, device=self.device), \
               torch.tensor(label_mask_list, device=self.device)

    def configure_callbacks(self):
        early_stop_callback = EarlyStopping(monitor="val_f1", min_delta=0.00, patience=self.args.patience,
                                            verbose=False, mode="max")

        if self.args.save_model:
            checkpoint_callback = ModelCheckpoint(monitor='val_f1',
                                                  dirpath="{}".format(self.save_log_path),
                                                  # filename='best-{epoch:02d}-{val_acc:.3f}',
                                                  filename='best_{}'.format(self.index_times),
                                                  save_top_k=1,
                                                  mode='max',
                                                  save_last=False)
            return [checkpoint_callback, early_stop_callback]
        else:
            return [early_stop_callback]

    def on_train_start(self):
        self.print("Training is started!")

    def on_train_end(self):
        self.print("Training is done!")

My dataset is:
class Ner_Dataset(Dataset):
   def __init__(self, data, language, desc='train'):
       super().__init__()
       self.data = load_json(dir=os.path.join('Data/' + data, language, desc + '.json'))
       self.clean_data = [one for one in self.data if one['tokens']]

   def __getitem__(self, item):
       tokens = self.clean_data[item]['tokens']
       ner_tags = self.clean_data[item]['ner_tags']
       return {"tokens": tokens, 'ner_tags': ner_tags}

   def __len__(self):
       return len(self.clean_data)

The version is :
**
transformers                  4.12.3
pytorch-lightning             1.6.3
torch                         1.9.1
**
The error is :
Training is started!
Epoch 0:   0%|                                                                                | 0/20 [00:00<?, ?it/s] the bert inputs============={'input_ids': tensor([[  101, 10979, 46006,  ...,     0,     0,     0],                                                                 | 0/5 [00:19<?, ?it/s]
[  101,   143, 36545,  ...,     0,     0,     0],
[  101, 32134,   125,  ...,     0,     0,     0],
...,
[  101, 11589, 10403,  ...,     0,     0,     0],
[  101, 13536,   112,  ...,     0,     0,     0],
[  101, 39981, 10108,  ...,     0,     0,     0]], device='cuda:0'), 'token_type_ids': tensor([[0, 0, 0,  ..., 0, 0, 0],
[0, 0, 0,  ..., 0, 0, 0],
[0, 0, 0,  ..., 0, 0, 0],
...,
[0, 0, 0,  ..., 0, 0, 0],
[0, 0, 0,  ..., 0, 0, 0],
[0, 0, 0,  ..., 0, 0, 0]], device='cuda:0'), 'attention_mask': tensor([[1, 1, 1,  ..., 0, 0, 0],
[1, 1, 1,  ..., 0, 0, 0],
[1, 1, 1,  ..., 0, 0, 0],
...,
[1, 1, 1,  ..., 0, 0, 0],
[1, 1, 1,  ..., 0, 0, 0],
[1, 1, 1,  ..., 0, 0, 0]], device='cuda:0')}=============
==============the bert output ======== tensor([[[nan, nan, nan,  ..., nan, nan, nan],
[nan, nan, nan,  ..., nan, nan, nan],
[nan, nan, nan,  ..., nan, nan, nan],
...,
[nan, nan, nan,  ..., nan, nan, nan],
[nan, nan, nan,  ..., nan, nan, nan],
[nan, nan, nan,  ..., nan, nan, nan]],
    [[nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     ...,
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan]],

    [[nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     ...,
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan]],

    ...,

    [[nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     ...,
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan]],

    [[nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     ...,
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan]],

    [[nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     ...,
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan],
     [nan, nan, nan,  ..., nan, nan, nan]]], device='cuda:0',
   grad_fn=<NativeLayerNormBackward>)===================


text:
Q: JS find all previous items of target item How do I find all the previous items from the array by target item via javascript?
Suppose I have an array of items ["Volvo", "BMW", "Mercedez", "Suzuki", "Honda"] and if my target value is Suzuki I should get ["Volvo", "BMW", "Mercedez"]
Thank you!

A: You can use Array#findIndex to find the index of the item you're looking for in the array, and then use Array#slice to get the result you're looking for.

const array = ["Volvo", "BMW", "Mercedez", "Suzuki", "Honda"];

const index = array.findIndex(v => v === 'Suzuki');

const result = array.slice(0, index);

console.log(result);

A: You can make use of the array methods array.slice() and array.indexOf()

const data = ["Volvo", "BMW", "Mercedez", "Suzuki", "Honda"];

const result = data.slice(0, data.indexOf("Suzuki"));

console.log(result);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closest Pair Algorithm in Python: difficulty sorting by x and y coordinates I'm trying to define a function that takes an array, consisted of points with x and y coordinates, as input. I need 2 outputs: one array that has the points sorted by their x coordinates and another array that has the points sorted by their y coordinate. I'm doing it in python. Thanks.

A: I'm going to assume that your array looks like the following:
input = [(1,2), (3,4), ..., (x,y)]

You can use the sorted method (built-in) to accomplish list sorting:
x_sorted = sorted(input, key=lambda tup: tup[0])
y_sorted = sorted(input, key=lambda tup: tup[1])

Where the lambda will sort your variable by the first and second indices, respectively

A: Alternatively, you can use the itemgetter()  function as the key parameter to the sorted() function:
from operator import itemgetter

points = [(7,3), (2,1), (4,5), (9,0)]
sorted_by_x = sorted(points) # you can add the key parameter itemgetter(0) if you want
sorted_by_y = sorted(points, key=itemgetter(1))

print("Points List: {}".format(points))
print("Sorted by X Points List: {}".format(sorted_by_x))
print("Sorted by Y Points List: {}".format(sorted_by_y))

Output:
Points List: [(7, 3), (2, 1), (4, 5), (9, 0)]
Sorted by X Points List: [(2, 1), (4, 5), (7, 3), (9, 0)]
Sorted by Y Points List: [(9, 0), (2, 1), (7, 3), (4, 5)]


text:
Q: A bug of mutable.Set.foreach in scala? I'm using scala 2.9.1, when I try this code:
import scala.collection.mutable
val a = mutable.Set(1,2,3,4,7,0,98,9,8)
a.foreach(x => { println(x); a.remove(x) })

the result was something like
0
98
2
1
4
3
8

which did not list all the elements of a. After this, a becomes Set(9, 7) instead of empty set. It looks very weird to me, is it a bug or we just cannot modify the set itself when doing foreach?

A: You may not modify a collection while traversing or iterating over it.
This is the same in Scala as it is in Java (and most other programming languages/libraries). Except that in Java, the Iterator class provides a remove method that can be used instead of the collection's remove method to remove elements while iterating using that Iterator (but will invalidate any other iterators of that collection that might be in use). Scala Iterators provide no such method.


text:
Q: Accessing network location on domain My computer is connected to a university network, in the computer science department. This domain is called "cs". However, "cs" is a subdomain of the whole university network, "myuni". For example, let's imagine the website for the department is www.cs.myuni.edu.
Now, if I want to access a directory on the "cs" domain, I open a terminal and type in cd /cs/shared_directory1, which is fine. But what if I want to access a directory on the "myuni" domain? Would I type in cd /myuni/shared_directory2, cd //myuni/shared_directory2, or something else? Or is it not possible because, perhaps, you can only access locations on one domain above you, not two?

A: In fact, organizations of domains and subdomains, and organization of the file system of the computer you are using are totally decorrelated. Your system administrators have apparently chosen to have a directory called cs at the root of the file system but that has nothing to do with the network you are in, except being a good way to remember it.
You will have to ask the people in your university responsible for the system/network where the files you are looking for are.


text:
Q: How to draw sequence of shapes with arrows and text I'm trying to draw something of the sort

with a square figure in the far left, and a rectangular figure cut into 4 slices on the right-hand side. Above the arrows and below the figures reads "text". The middle portion consists of $\Omega_i$'s, with arrows coming from $\Omega_1$, $\Omega_j$, and $\Omega_k$.
How would one draw such a figure?

A: You can use TikZ:

The code:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,calc,matrix,shapes.multipart}

\begin{document}

\begin{tikzpicture}[
node distance=1cm and 1.5cm,
arrow/.style={
  ->,
  >=latex,
  shorten >= 3pt,
  shorten <= 3pt,
}
]
\node[draw,minimum size=3cm,label={270:text}]
  (rect) {};
\coordinate[right=of rect] (aux);
\matrix[matrix of math nodes]
  at ([xshift=8pt]aux)
  (mat)
  {
    \Omega_i \\
    \vdots \\
    \Omega_j \\
    \vdots \\
    \Omega_k \\
  };
\node[draw,rectangle split,rectangle split horizontal=true,right=1.5cm of mat,minimum size=1cm,label={270:text}]
  (rectiv) {};
\node[circle,draw,right=of rectiv,minimum size=1cm,label={270:text}]
  (circ)  {};
\draw[arrow]
  (rect) -- node[above] {text} (aux);
\foreach \Valor/\Texto/\Pos in {1/texti/above,3/textj/above,5/textk/below}
{
\draw[arrow]
  (mat-\Valor-1.east) -- node[pos=0.3,\Pos,sloped] {\Texto} (rectiv.west);
}
\draw[arrow]
  (rectiv) -- node[above] {text} (circ);
\end{tikzpicture}

\end{document}

A: Here's another version using nodes and arrows.
Output

Code
\documentclass[margin=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,shapes.multipart,positioning}

\tikzset{
    split/.style={rectangle split, rectangle split parts=4,
        rectangle split horizontal, rectangle split empty part width=4mm},
}

\begin{document}
\begin{tikzpicture}[node distance=2cm, -{Straight Barb}]

\node[draw, minimum width=4cm, minimum height=3cm, label=270:text] (big) at (0,0) {};
\node[right =of big] (oj) {$\Omega_j$};
\node[below =1.5cm of oj] (ok) {$\Omega_k$};
\node[above =1.5cm of oj] (oi) {$\Omega_i$};
\node[draw, split, minimum width=4cm, minimum height=2cm, label=270:text, right =of oj] (multi) {};
\node[draw, circle, minimum size=4cm, right =of multi,label=270:text] (circ) {};

% lines and arrows
\draw (big) -- (oj) node[above, midway] {text};
\draw[-, thick, loosely dotted] (ok) -- (oj) -- (oi);
\draw (oj) -- (multi.west) node[above, midway] {text};
\draw (oi) -- (multi.160) node[above, midway, sloped] {text};
\draw (ok) -- (multi.200) node[above, midway, sloped] {text};
\draw (multi) -- (circ);

\end{tikzpicture}
\end{document}

A: The chains library offers another possibility, especially convenient when used in conjunction with the quotes and scopes libraries. Nodes on chains are automatically named using the name of the chain and the count of nodes on that chain. Here, I call the chain c1 so the nodes are c1, c2 etc.
I also use two branches, c2 and c3. The nodes on branches are named <chain name>/<branch name>-<count of nodes on branch> e.g. c1/c2-2 means the second node on branch c2 of chain c1.
A few styles are offered for convenience, and to ensure consistency in the placement and style of nodes, labels and edges.
Most edges are drawn using the join option from the chains library. The exceptions are the two diagonal arrows which it seemed easier to draw by hand.
For example:
\documentclass[tikz,border=10pt]{standalone}
\usetikzlibrary{chains,arrows.meta,scopes,shapes.multipart,quotes}

\begin{document}
\begin{tikzpicture}
  [
    start chain=c1 going right,
    every on chain/.style={join},
    every edge/.append style={font=\scriptsize, shorten >=5pt, shorten <=5pt},
    >={Stealth[]},
    my join/.style={join=by {"#1"}},
    every edge quotes/.append style={midway, sloped, anchor=south},
    node distance=1 and 2,
  ]
  {[every join/.append style={->}]
    \node [on chain=c1, label=-90:text, text height=40pt, text width=40pt, draw] {};
    \node [on chain, my join=text] {$\Omega_j$};
    { [start branch=c2 going above ] }% manual 54
    { [start branch=c3 going below ] }
    \node [on chain, label=-90:text, draw, minimum height=20pt, rectangle split, rectangle split horizontal, rectangle split parts=4, rectangle split ignore empty parts=false, my join=textj] {};
    \node [on chain, label=-90:text, draw, circle, minimum size=20pt, my join=text] {};
  }
  {[every join/.append style={densely dotted}]
    {[continue branch=c2]
      \node [on chain] {$\Omega_i$};
    }
    {[continue branch=c3]
      \node [on chain] {$\Omega_k$};
    }
  }
  \draw (c1/c2-2) edge [->, "texti"] (c1-3.west);
  \draw (c1/c3-2) edge [->, "textk"] (c1-3.west);
\end{tikzpicture}
\end{document}


text:
Q: XStream issue with implicit collections I have the following XML:
<appConfig>
    <database isSource="true" fizz="129"/>
    <database isSource="false" fizz="29494" />
    <buzz bee="always" />
</appConfig>

That should map to the following POJOs:
public class AppConfig {
    private Database sourceDb;
    private Database targetDb;
    private Buzz buzz;
}

public class Database {
    // Omitted for brevity...
}

public class Buzz {
    // Omitted for brevity...
}

And have configured the following XStream mapper:
XStream oxMapper = new XStream();
oxMapper.alias("appConfig", AppConfig.class);
oxMapper.alias("database", Database.class);
oxMapper.alias("buzz",  Buzz.class);

To read and deserialize the XML like so:
ApplicationConfig appCfg = (ApplicationConfig)oxMapper.fromXML(
        getXMLSnippet());

But am getting this error:
Element database of type com.myapp.Database is not defined as field in type com.myapp.AppConfig

I read this article which talks about implicit collections, and believe that XStream thinks my two Database items are a part of a list (implicit collection) when in fact they are not (they should map to 2 different AppConfig properties).
How do I fix this? Thanks in advance!

A: You have to set aliases by the name of field, not the type.
For your example it should be:
oxMapper.alias("sourceDb", Database.class);
oxMapper.alias("targetDb", Database.class);
oxMapper.alias("buzz",  Buzz.class);


text:
Q: Android studio is not showing any android related options I don't know what happened but suddenly i started getting these error messages.
Plugin Error
                    Problems found loading plugins:
                    Plugin "Android Games" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Android NDK Support" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Android APK Support" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Google Developers Samples" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Google Cloud Tools For Android Studio" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Test Recorder" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Firebase Testing" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Google Services" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Firebase Services" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "App Links Assistant" was not loaded: required plugin "Android Support" is disabled.
                    Plugin "Fire... (show balloon)

and I am just unable to create any new android app, or run the current app.
This is what i am getting when trying to create a new project.

There are also no android avd sdk manager options available.
I have just updated Android Studio and now using 3.1.3

A: The log has already tell you what the problem is,

required plugin "Android Support" is disabled.

Then you just need to enable it. In the Plugin page of Settings, tick the plugin Android Support, then OK and Restart Android Studio.


text:
Q: Getting the Named Anchor using ColdFusion How can I get the URL using ColdFusion?
I tried the following but it did not return the Named Anchor.
For example http://www.makeup.edu/test/#abc
<cfdump var=#cgi#>

A: You can't, 'cause although it is in the URL, it is only meant for the client.  It will not be sent to the server, therefore you can never find that in the CGI scope.

A: As Henry says, you can't get them with ColdFusion because they are never sent with the request. What you need to do is to pull them out with Javascript (which can access them), and then send them back to the server via some other mechanism, like putting them in a cookie or something. It depends on the situation as to how you tackle that part, but it's probably a different question anyhow.
Bottom line: the info is never transmitted with the request, so the web server doesn't get it, so the web server cannot pass it to ColdFusion, so ColdFusion does not receive it.

A: Add an additional url parameter to identify the anchor. So you could create the link http://www.makeup.edu/test/?anchor=1#abc
The user clicks on the link and the anchor goes to the right place and then you could use:
<cfif ISDEFINED("url.anchor")>
  <cfif url.anchor EQ 1>
     ... do stuff here...
  </cfif>
</cfif>


text:
Q: overloadded method on a class template, always gives unable to match function definition to declaration I'm somehow new to templates and I'm trying to modify some library that provide matrix and vector operation to c++, i have a vector class which I'm trying to overload the operator() for it to handle an operation like this Vector(2:5) will return a vector that has elements 2,3,4,5 of the original vector, and I'm using a class called colon where colon(2:5) will represent the (2:5) effect as i found that c++ has no operator: .
hope i gave a proper introduction.
The relevant code is as follows
The Vector Class
template< size_t M, typename T = float >
class Vector
{
public:
typedef T   value_type;
Vector operator-( const Vector& other ) const;
template <size_t N, typename T> Vector<N,T> operator()(const  colon &cex) const;
.
.
}

and the corresponding implementation
template< size_t M, typename T >
template< size_t N,T>
Vector<N,T>
Vector<M,T>::operator()( const colon &cex ) const
{
long i, ii, st = 0, in = 0, en = 0, s;
cex.apply(M, st, in, en, s);
if (s && (st>0) && (st>M))
{
Vector<N,T> result;
for (i=st,ii=0;i+=in,ii++;i<=en,ii<N)
{
result(ii)=array(i);
return result;
}

}
return 0;
}

the return 0 here is just a place holder, it should return an empty vector.
the colon class (which is taken from another library and modified by me).
class colon
{
public:
/// Colon expression '(:)'
colon() { _flag = 'a'; }
/// Colon expression of type '(2:5)'
colon(long s, long e) { _s = s; _i = 1; _e = e; _flag = 'r'; }
void apply(long s, long &f, long &i, long &l, long &n) const;

private:
/// Type of colon expression.
char _flag;
/// First index.
long _s;
/// Increment.
long _i;
/// Last index.
long _e;

}; /* class colon */

and the relevant implementation is
void
colon::apply(long n, long &st, long &in, long &en,
     long &le) const
{
switch (_flag)
{
    case 'r':
        if ((_i == 0 ) || ((_e - _s) / _i < 0 )) le = 0;
        else
        {
            st = _s;
            in = _i;
            en = _e - (_e - _s) % _i;
            le = (_e - _s) / _i + 1;
        }
        break;
    case 'a':
        if (n)
        {
            st = 1;
            in = 1;
            en = n;
            le = n;
        }
        else le = 0;
        break;

 }
}

when compiling this code i always receive the error
Error   1   error C2244: 'Vector::operator ()' : unable to match function definition to an existing declaration
and the output of the compiler is
error C2244: 'Vector<M,T>::operator ()' : unable to match function
definition to an existing declaration

definition
'Vector<N,T> Vector<M,T>::operator ()(const colon &) const'

existing declarations
'Vector<N,T> Vector<M,T>::operator ()(const colon &) const'

So What I'm doing wrong here?

A: In your declaration you write:
template< size_t M, typename T = float >
class Vector
{
template <size_t N, typename T>
Vector<N,T> operator()(const  colon &cex) const

and in your definition you write:
template< size_t M, typename T >
template< size_t N,T>
Vector<N,T>
Vector<M,T>::operator()( const colon &cex ) const

Notice the difference in the second template line:
template <size_t N, typename T>

vs.
template< size_t N,T>

You are missing the typename there. So instead of passing a type to T you expect to get passed an instance of  T (which is only possible if T is an integral type).
This shows that your declaration and definition do in fact differ and where the error originates from.
As your second T would hide the first (which is not allowed - see comments), I think you either want to rename the second Tand add the typename in the definition or you want to remove the second T altogether.

A: First problem is that you write template function arguments wrong: template<size_t N,T>. It shall be template<size_t N, typename T>, otherwise it will be considered as non-type template parameter (some specific value of T).
Second problem is that function template parameter name T is ambiguos. Compiler could not know which T it shall use, from class template parameter or from function one? Remember, function and class template parameters are unrelated. So you need to rename it:
template<size_t M, typename T> class Vector
{
public:

template <size_t N, typename X> Vector<N,X> operator()() const;
};

template<size_t M, typename T>
template<size_t N, typename X> Vector<N,X> Vector<M,T>::operator()() const
{
}

But actually if you don't need cross-type operations and X will be always the same type as T you could just skip it in function and parametrize it only by size:
template<size_t M, typename T> class Vector
{
public:

template <size_t N> Vector<N,T> operator()() const;
};

template<size_t M, typename T>
template<size_t N> Vector<N,T> Vector<M,T>::operator()() const
{
}


text:
Q: Изменение высоты UINavigationBar как в приложении Messages Каким образом можно достичь того же эффекта, с изменением высоты UINavigationBar и "переползанием" заголовка, как в приложении Apple Messages?

A: раздел Navigation Bar Titles:
https://developer.apple.com/design/human-interface-guidelines/ios/bars/navigation-bars/
override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        navigationController?.navigationBar.prefersLargeTitles = true
}


text:
Q: The non-generic method 'HttpClient.GetAsync(string)' cannot be used with type arguments I have this code which register HttpClient
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();

        services.AddHttpClient("ServerAPI", client =>
            client.BaseAddress = new Uri("http://localhost:xxxxx/"));
    }

and to use it, I injected it at my Blazor razor page,
@page "/Movies/FetchMovies"
@inject IHttpClientFactory http;
@using System.Text.Json

<MovieList Movies="movies" />

@code{
    private List<Movie> movies;

    protected override async Task OnInitializedAsync()
    {
        var client = http.CreateClient("ServerAPI");
        movies = await client.GetAsync<List<Movie>>("api/Movies");

        //movies = await client.GetFromJsonAsync<List<Movie>>("api/Movies");
    }
}

Problem is this line movies = await client.GetAsync<List<Movie>>("api/Movies"); gets an error:
The non-generic method 'HttpClient.GetAsync(string)' cannot be used with type arguments
I tried with movies = await client.GetFromJsonAsync<List<Movie>>("api/Movies") but also get an error.

A: If you wish to use the GetFromJsonAsync method instead, do the following:

*

*Install the package System.Net.Http.Json

*reference the namespaces: System.Text.Json and System.Net.Http.Json
either to your specific razor file, or to the /_Imports.razor file.
Now this code will the job...
movies = await client.GetFromJsonAsync<List<Movie>>("api/Movies");

A: You should do that like this:
@code{
    private List<Movie> movies;

    protected override async Task OnInitializedAsync()
    {
        var client = http.CreateClient("ServerAPI");
        var response= await client.GetAsync("api/Movies");
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStreamAsync();

        movies = await System.Text.Json.JsonSerializer.DeserializeAsync<List<Movie>>
                      (responseContent,
             new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
    }
}

Hope this helps...


text:
Q: Background-position: Not applying to mobile browsers I'm doing some responsive work and can not figure out why this isnt applying to my phones browsers.
Heres what I'm using to shift the images (They shift properly on desktop when I scale down)
 .element {
    background-image: url("/image");
    min-height: 1000px;
    background-position: 0% 100%;
 }

So, this looks perfect on desktop when I scale down to it.. However, If I load it up in Chrome/Safari on my IPhone6.. The position does not take effect.. The background and the min-height change.
For reference, the height of the image is much taller than the min-height.
I'm at a loss here.


text:
Q: How to ajax submit this form which doesn't have a submit button? I have the following form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input name="uploadedfile" type="file" />
</form>

Once a user has clicked the uploadedfile input and selected a file, they then can click this button on a different area of the page:
My button

How can clicking My button, how can it trigger the upload of the form? Important:  cannot be within the form and can't be an input element. This must also be an ajax style operation with no reloading of the page if possible.

A: You can give the form an ID (or use one of the many variations to select the form):
<form id="myForm" [...] >

and with jQuery submit the form:
$('#myForm').submit();

You'll want the submit functionality to be within a click event of the button:
$('#button').click(function(){
    $('#myForm').submit();
});

Update
To submit your form using ajax you can do the following:
$('#button').click(function(){
      var form = $('#myForm');
        $.ajax({
          url: form.attr('action').val()  ,
          type: 'POST' ,
          data: form.serialize()
        });
    });

If you're uploading files as it seems you might be, you might want to look at one of the following jQuery plugins:

*

*jQuery Ajax File Upload Plugin

*Multiple File Upload Plugin

A: Simply get a reference to the form and then call .submit on it:
$("#button").click(function() {
    $("form[action='uploader.php']").submit();
});

It would be a good idea to give the form an id as well so that you can select it with a more mainstream selector such as $("#theForm").

A: You can use jQuery trigger function
$("#button").click(function(){
    $("form").trigger('submit');
});

Check Demo here

A: you can do like the above answers, or you can submit the form without even refreshing the page like HERE


text:
Q: Future work and developer documentation In your opinion, should the documents listing what further needs to be done on the application development separate from the developer documentation describing design decisions and algorithms? It would be great to also explain the reason for the opinion on why it's clearer to do or not do so. Thanks in advance for the comments.

A: Yes, documentation of the existing system and documentation of prospective future changes should be separate.
The most important documentation is what the current system is, and what it does.  Prospective changes don't provide anything of value from a maintenance perspective - just clutter.  Prospective changes may be determined to be of lesser importance depending on various factors (most likely being money to fund), and timelines are adjusted accordingly.


text:
Q: How does one find all the fixed points of the Hodgkin-Huxley Model? I'm trying to find the fixed points of the Hodgkin-Huxley model, given by the system of equations:
$$
dV/dt=f_V(V,m,h,n)=\frac{1}C_M[I_{ext}-\bar{g}_{Na}m^3h(V-V_{Na})-\bar{g}_Kn^4(V-V_K)-\bar{g}_l(V-V_l)],
$$
$$
dm/dt=f_m(V,m)=α_m(V)(1-m)-β_m(V)m,
$$
$$
dh/dt=f_h(V,h)=α_h(V)(1-h)-β_h(V)h,
$$
$$
dn/dt=f_n(V,n)=α_n(V)(1-n)-β_n(V)n
$$
with,
$$
α_m(V) = \frac{(V+45)/10}{(1-\exp(-(V+45)/10)}
$$
$$
β_m(V) = 4\exp(-(V+70)/18)
$$
$$
α_h(V) = 0.07\exp(-(V+70)/20)
$$
$$
β_h(V) = \frac{1}{1+\exp(-(V+40)/10)}
$$
$$
α_n(V) = 0.1\frac{(V+60)/10}{1-\exp(-(V+60)/10)}
$$
$$
β_n(V) = 0.125\exp(-(v+70)/80)
$$
and
$$
C_M = 1,
$$
$$
\bar{g}_{Na} = 120
$$
$$
\bar{g}_K = 36,
$$
$$
\bar{g}_l = 0.3,
$$
$$
V_{Na} = 45,
$$
$$
V_K = -82,
$$
$$
V_l = -59
$$
I went ahead and set the derivatives to zero, and solved for $V$, $m$, $n$, and, $h$ in MatLab using vpasolve. I got a single fixed point at $(-69.898, 0.593, 0.054, 0.319)$. However, in my research, (Wang, Chen, Fei. Analysis and Control of the Bifurcation of the Hodgkin-Huxley Model, Table 2) I see results yielding three fixed points. Moreover, one of these fixed points should correspond with the stable resting potential of the cell membrane, which in my model is found to be $-66.831$, which does not even correspond with the one fixed point I did find. I would really appreciate any guidance as to where I may have gone wrong, but I apologize in advance for formatting issues or if my question is misguided.


text:
Q: How can i select the complete row for different components in UIPickerView? I have 4 components in PickerView. I want to select the complete row in all the components when row 0 of component 0 is selected. Similarly, for every other row of each components. Is there any way to extend the single selection for all?
Any help would be appreciated.

A: Implement the UIPickerView delegate method pickerView:didSelectRow:inComponent:.
// called when a user selects a row
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    // This code assumes all four components have the same number of rows
    for (NSInteger c = 0; c < pickerView.numberOfComponent; c++) {
        if (c != component) {
            [pickerView selectRow:row inComponent:c animated:NO]; // animate if desired
        }
    }

    // do any other desired actions (if any) when a row is selected
}

Another option would be to have just one component showing all four sets of data in each row. Having 4 components doesn't make a lot of sense if the user can't ever select different values for each component.


text:
Q: tkinter open canvas inside Frame I have a canvas which is opening in the main window, but I want it to open in the canvas inside the Frame. I tried to add some crazy (as they're in my hands) attributes, but they didn't solve my problem, so I deleted them and have no idea what to do. Could you help me - how could I realize it?
code:
from tkinter import *
from tkinter import ttk

class Example(Frame): # Frame
 def __init__(self, root):
    Frame.__init__(self, root)

    # ---- for grid ----
    canvas_width = 1000  # MUTABLE!!!
    canvas_height = 1000  # MUTABLE!!!
    self.canvas_width = canvas_width
    self.canvas_height = canvas_height

    self.warehouse_canvas = Canvas(self, width=canvas_width, height=canvas_height, background="bisque")
    self.x_scrollbar = Scrollbar(self, orient="horizontal", command=self.warehouse_canvas.xview)
    self.y_scrollbar = Scrollbar(self, orient="vertical", command=self.warehouse_canvas.yview)
    self.warehouse_canvas.configure(yscrollcommand=self.y_scrollbar.set, xscrollcommand=self.x_scrollbar.set)
    self.warehouse_canvas.configure(scrollregion=(0, 0, canvas_width, canvas_height)) # c_w c_h изменены

    self.x_scrollbar.grid(row=1, column=0, sticky="ew")
    self.y_scrollbar.grid(row=0, column=1, sticky="ns")
    self.warehouse_canvas.grid(row=0, column=0, sticky="nsew")
    self.grid_rowconfigure(0, weight=1)
    self.grid_columnconfigure(0, weight=1)

    root.columnconfigure(1, weight=1)
    root.rowconfigure(1, weight=1)

    self.warehouse_canvas.bind("<ButtonPress-1>", self.scroll_start)
    self.warehouse_canvas.bind("<B1-Motion>", self.scroll_move)

    self.draw_grid(self.warehouse_canvas, canvas_width, canvas_height) # !!!

def draw_grid(root, warehouse_canvas, canvas_width, canvas_height):
    for line in range(0, canvas_width, 10):
        warehouse_canvas.create_line([(line, 0), (line, canvas_height)], fill='#d9d9d9', tags='grid_line_width')
    for line in range(0, canvas_width, 10):
        warehouse_canvas.create_line([(0, line), (canvas_width, line)], fill='#d9d9d9', tags='grid_line_height')
    # warehouse_canvas.grid(row=0, column=0)               color :  #d9d9d9

def scroll_start(self, event):
    self.warehouse_canvas.scan_mark(event.x, event.y)

def scroll_move(self, event):
    self.warehouse_canvas.scan_dragto(event.x, event.y, gain=1)

if __name__ == "__main__":
   root = Tk()

   Example(root).grid(row=0, column=0, # положение
                   columnspan=2, rowspan=2, sticky="nsew")

   root.mainloop()

What I have
Where I want it to be
Is there any way to do it without rewriting the whole code?


text:
Q: ubuntu 14.04 strange things happening so I have some kind of problem with my ubuntu 14.04 64 bit. file mannager keeps crashing and some of the apps has a different layout for example system monitor looks weird:

file explorer does the same thing occasionally, what is happening and how to resolve it?
here is another img:

A: The transparent window is as a result of Gnome PPA, remove it from Software and Updates and run sudo apt-get update then log-off and login again.
if you like to know with more thorough answer, go here


text:
Q: Finding the status of scanner through PHP code In our application we need to scan some documents and it should save to disk directly.
Now we need to make one button to scan. That button should find the status of scanner.
If the status of scanner is connected it's should proceed and it's not connected it should display some errors like Scanner not connected when I click the button.

A: You should make use of phpSANE. It's available on SourceForge and it does all what you have mentioned in the context so you don't have to code it again.


text:
Q: Javascript class passing parameters I have been creating several classes but I never had any that needed parameters on the class itself.
The following code works perfectly.
$(function()
{
   search.anotherFunction('a', 'b');
});

search = function()
{

   this.anotherFunction = function(param1, param2)
   {
      // do whatever
   };

   var public = { anotherFunction: anotherFunction }

   return public;
}();

But now I would like to pass parameters inside search in order to avoid passing the same parameters to all the functions.
$(function()
{
   search('front/file.php').anotherFunction('a', 'b');
});

search = function(url)
{

   this.anotherFunction = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   this.anotherFunctionB = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   var public = { anotherFunction: anotherFunction,
                  anotherFunctionB: anotherFunctionB }

   return public;
}();

This doesn't work and the console outputs the error.

Uncaught TypeError: object is not a function

It means that search isn't a function but yes a class name and therefore can't receive params?

A: To start with, the way you're creating your "classes" is incorrect, and ends up creating global variables: Inside the call to your anonymous function, because of the way you call it, this will refer to the global object*, so this.anotherFunction = ... will create a global variable called anotherFunction, because properties on the global object are global variables.
If you want to keep using your current pattern with minimal changes, then don't use this.xyz = ... with your functions, use var instead:
var search = function()
{
   var anotherFunction = function(param1, param2)
   {
      // do whatever
   };

   var public = { anotherFunction: anotherFunction }

   return public;
}();

Also note that you were falling prey to The Horror of Implicit Globals by not declaring search; I've added a var to declare it.
Your second example, with the changes above, would work if you didn't call the outermost function and just assigned the function to the search variable, then called it later:
var search = function(url)
{

   var anotherFunction = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   var anotherFunctionB = function(param1, param2)
   {
      // use here the 'url' parameter
   };

   var public = { anotherFunction: anotherFunction,
                  anotherFunctionB: anotherFunctionB }

   return public;
}; // <== Note, no () here

Now search refers to a function, which we can call like this:
var x = search("http://example.com");
x.anotherFunction(...); // Will have access to the URL

* Why does this refer to the global object when you call your anonymous function? Because you call it without doing anything to set this to something else, and you're using loose mode. (I know you're using loose mode because if you were using strict mode, this would be undefined and so this.anotherFunction = ... would fail.)

Side note: I would recommend you stop using public as a variable name, as it's a future reserved word and has been since at least ES3.

A: You can use JavaScript closures here. Check out the below approach:
search = function()
{
    return function (url) {
       this.anotherFunction = function(param1, param2)
       {
          // use here the 'url' parameter
       };

       this.anotherFunctionB = function(param1, param2)
       {
          // use here the 'url' parameter
       };

       var public = { anotherFunction: anotherFunction,
                      anotherFunctionB: anotherFunctionB }

       return public;
    }
}();

search('front/file.php').anotherFunction('a', 'b');


text:
Q: Delphi7 Font dialog outdated on Windows 7
*

*Left - dialog of Win7 of modern apps

*Right - dialog of Win7 of my Delphi7 app

How to make my dlg modern? (How to patch Delphi7)

A: The offending part for the new dialog to be shown, for Windows 7 and later, is the callback. Here's a quote from "Font Dialog Box":

If you enable a hook procedure without creating a custom template, the
  default ChooseFont template for earlier Windows versions will be
  loaded.

You can eliminate the hook procedure by modifying a copy of "dialogs.pas" and putting it in your source folder for the current project.
function TFontDialog.Execute: Boolean;
  ...
//    Flags := Devices[FDevice] or (CF_INITTOLOGFONTSTRUCT or CF_ENABLEHOOK);
    Flags := Devices[FDevice] or CF_INITTOLOGFONTSTRUCT;
  ...
//    hWndOwner := Application.Handle;
    hWndOwner := GetActiveWindow;
  ...

The latter modification is for displaying the dialog in a reasonable place. Once the hook procedure is disabled, the VCL will not be able to center the dialog. You will also lose "Apply" button functionality and other events (OnShow/Close).


text:
Q: I want to send html type in email body with gmail sender i want to send email using html code.
plzz help
GMailSender m = new GMailSender("", "");
    String[] toArr = {""};
    m.setTo(toArr); // load array to setTo function
    m.setFrom("dawinderg@gmail.com"); // who is sending the email
    m.setSubject("Registration");
    m.setBody("Thanks for registration with us.");

i want to send +username+ this code in m.setBody().
how can i do this??

A: You can use this:
m.setBody(Html.fromHtml("
Title

Username "+ username +" and password"));

You can also create html tables or any other html elements
If the example is from here: GMailSender example
Change
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
withDataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/html"));
and add the body like this:
m.setBody("
TESTING
");


text:
Q: for loop is not working in JSP

            ID
            Date
            To Account
            From Account
            Amount
            Notes

        <% ArrayList list = (ArrayList) request.getAttribute("data")%>

        <% for(int i=0;i<list.size();i++){%>

             <%= list.get(i)%>

        <% } %>

I am getting an error on the for loop line in my netbeans IDE.  It is suggesting that I need a ";" somewhere but I do have it correct don't I?
After posting this I figured out that I was missing the semi-colon in the directive jsp tag.  But now I am getting an error that the page is missing the request object?  How can this be?  I thought it was an implicit object?

A: You are getting an error on the for loop line because you didn't close the previous statement with a semicolon. This one:
<% ArrayList list = (ArrayList) request.getAttribute("data")%>

Which should have a semicolon at the end, like this:
<% ArrayList list = (ArrayList) request.getAttribute("data");%>

A: Statements within { block } must end with ; , just the same way it is in Java, because they are indeed Java statements. JSP is getting translated and compiled into Java code (Servlet) by container (Tomcat)
Correct form is <% ArrayList list = (ArrayList) request.getAttribute("data"); %>
Just for information, in JSP,  declarations can take three different forms:
<% int a = 1; %>       // variable created for each HTTP request
<%! int b = 2; %>      // variable created for each servlet instance
<%! static c = 3; %>   // static variable shared by all instances of servlet

In any form, it has to be closed with ;
Note that on the other hand an expression <%= %> is not a Java statement, so accordingly, expression block <%= ... %> does not require no semicolon at the end.
Also make sure that you have added import for ArrayList on the top of the JSP page, as by default JSP page has access only to java.lang.* package
<%@ page import="java.util.ArrayList"%>


text:
Q: Quantum Field Theory Commutation Relations Let $ϕ(x,t)$ denote the canonical fields and $π(x,t)$ denote the canonical momenta where they're given by:
\begin{equation}
\phi(x)=\int\frac{d^3\vec{p}}{(2\pi)^3\sqrt{2\omega_{\vec{p}}}}(a_{\vec{p}}e^{-ipx}+a_{\vec{p}}^{\dagger}e^{ipx})
\end{equation}
\begin{equation}
\pi(x)=-i\int\frac{d^3\vec{p}}{(2\pi)^3}\sqrt{\frac{\omega_{\vec{p}}}{2}}(a_{\vec{p}}e^{-ipx}-a_{\vec{p}}^{\dagger}e^{ipx})
\end{equation}
I am trying to prove the following relationships:
\begin{equation}
[\phi(\vec{x},t),\phi(\vec{y},t)]=0=[\pi(\vec{x},t),\pi(\vec{y},t)].\tag{2.90}
\end{equation}
I have already arrived at:
\begin{equation}
[\phi(\vec{x},t),\phi(\vec{y},t)]=\int\frac{d^{3}\vec{p}}{(2\pi)^{3}}\frac{1}{2\omega_{p}}(e^{ip(y-x)}-e^{-ip(y-x)})
\end{equation}
I know that the commutator is zero, but I am failed to interpret the above expression. Can someone help me out?

A: Because both field operators are being evaluated at the same time $t$, we have that $y-x = (0, \vec y - \vec x)$, and so $p \cdot (y-x) = \vec p \cdot (\vec y- \vec x)$. From here, note that $e^{i\vec p \cdot (\vec y - \vec x)}-e^{-i\vec p \cdot (\vec y - \vec x)}=2i\sin\big(\vec p \cdot (\vec y-\vec x)\big)$, which is an odd function of $\vec p$.  $\omega_p$ is an even function of $\vec p$, so the integrand as a whole is odd.  What happens when you integrate an odd function over all $\vec p$?

Note that it is reasonable to object on the grounds that this integral does not actually converge in the sense of ordinary improper integrals.  We must remember that, like the field operators themselves, this object is meant to be integrated against smooth and rapidly-decaying test functions.  In other words, the well-defined quantity is
$$\int \frac{\mathrm d^3p}{(2\pi)^3} \int \mathrm d^3x\ \int d^3 y\  \frac{1}{2\omega_p} \left(e^{i p \cdot ( y - x)} - e^{-i p\cdot ( y - x)}\right) f(\vec x) g(\vec y) $$
where the integrals over $x$ and $y$ are performed first. This object is a perfectly well-defined number (which can be straightforwardly shown to be equal to zero).
As a general rule, if you are concerned about the convergence or cancellation of integrals, then you can put your mind at ease by replacing $\phi(\vec x,t)$ with the more rigorously defined $\Phi_t(f) := \int \mathrm d^3 x \ f(\vec x) \phi(\vec x,t)$, with $f$ an aforementioned (arbitrary) test function.  It is somewhat inconvenient to carry around these arbitrary test functions, but it has the advantage of making the expressions you write down well-defined.  Your mileage may vary, of course.
In this language, we would have
$$[\Phi_t(f),\Phi_t(g)] = 0$$
$$[\Phi_t(f),\Pi_t(g) ] = i\int\mathrm d^3 x f(\vec x)g(\vec x)$$
for arbitrary test functions $f$ and $g$, which imply- and are implied by - the equal-time commutation relations
$$[\phi(\vec x,t),\phi(\vec y,t)] = 0$$
$$[\phi(\vec x,t),\pi(\vec y,t)] = i\delta(\vec x - \vec y)$$
for the bare field operators.


text:
Q: Simulator and Phone don't show the same matchedGeometryEffect result I have a very simple example where I want to make a square larger. In the simulator everything looks fine but when I run it on the phone the square becomes transparent.
On simulator
On phone
Content View
struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @Namespace var animation
    @State var isBig:Bool = false
    var body: some View {
        ZStack {
            Color(.red)
            if(!isBig){
                RectangleViewSmoll(isBig:$isBig, animation: animation)
            }
            if(isBig){
                RectangleViewBig(isBig:$isBig,animation: animation)
            }
        }
        .ignoresSafeArea()
    }
}

Small Rectangle
struct RectangleViewSmoll: View {
    @Binding var isBig:Bool
    var animation:Namespace.ID
    var body: some View {
        Rectangle()
            .matchedGeometryEffect(id: "rectangle", in: animation)
            .frame(width: 50, height: 50)
            .onTapGesture {
                withAnimation(.easeIn(duration: 2)){
                    isBig.toggle()
                }
            }
    }
}

Big rectangle
struct RectangleViewBig: View {
    @Binding var isBig:Bool
    var animation:Namespace.ID
    var body: some View {
        Rectangle()
            .matchedGeometryEffect(id: "rectangle", in: animation)
            .frame(width: 500, height: 500)
            .onTapGesture {
                withAnimation(.easeIn(duration: 2)){
                    isBig.toggle()
                }
            }
    }
}

A: The problem is with the animation line, try like this will fix your problem:
Rectangle()
            .matchedGeometryEffect(id: "rectangle", in: animation)
            .frame(width: 500, height: 500)
            .onTapGesture {
                isBig.toggle()
            }
            .animation(.easeIn(duration: 2))


text:
Q: Swift - How switch between storyboards with back button? I'm in a storyboard and I need to go to another storyboard by tapping a button. Well, this I've already done, but I need to go back to previous storyboard. Here is my code:
func goContact() {
    let storyboard = UIStoryboard(name: "FAQ", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "ContactViewController")
    self.navigationController?.show(vc, sender: nil)
}

By tapping a button on my UITableViewCell (where I have a protocol), this function (goContact) is called and I switch to another storyboard (FAQ). But, how can I go back to main.storyboard?
I've already tried do this too:
func goContact() {
    let storyboard = UIStoryboard(name: "FAQ", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "ContactViewController")
    self.navigationController?.show(vc, sender: nil)
    // self.navigationController?.pushViewController(vc, animated: true)
    // self.present(vc, animated: true, completion: nil)
}

A: Use only  storyboard property , it references to Main storyboard of the app or you can write it like let storyboard = UIStoryboard(name: "Main", bundle: nil)
To go back after push do
self.navigationController?.popViewController(animated: true)

A: You should push your new view controller onto the navigation controller using push, like in your commented-out code. That will cause the new view controller to have a back button, which will pop it for you without needing any extra code.


text:
Q: Clicking a website button (Chrome) that has no ID I am trying to automate a login process along with other things. I found this script somewhere but the button I'm trying to click has no ID.
tell application "Google Chrome"
    activate
    open location "https://members.merchinformer.com/login"
    set theTab to tab 1 of window 1
    repeat
        if (loading of theTab) is false then exit repeat
    end repeat
    set theURL to URL of theTab
    if theURL contains "login" then
        execute theTab javascript "document.getElementById('login-button').click();"
    end if
    end tell

I tried a bunch of methods to click it but with no success. Any way around it?

A: This script is the one that clicks it:
tell application "Google Chrome" to ¬
    tell active tab of front window to ¬
        execute javascript ¬
            "document.getElementsByClassName('btn btn-block btn-custom waves-effect waves-light')[0].click();"


text:
Q: Convert heterogeneous date character vectors to date format (R) I'm trying to convert a character column with dates to date format. However, the dates are in an ambiguous format. Some entries are of the format %d.%m.%Y (e.g., "03.02.2021"), while others are %d %b %Y (e.g., "3 Feb 2021").
I've tried as.Date(tryFormats=c("%d %b %Y", "%d.%m.%Y")), but realized that tryFormats is only flexible for the first entry, so that the entries of type %d %b %Y are correctly identified but those of %d.%m.%Y become NAs, or vice versa. I've also tried the anytime package, but that produced NAs in a similar fashion.
I've made sure that the column doesn't contain any NAs or empty strings, and I don't receive any error message.

A: Try the parsedate package :
df <-read.table(header=TRUE,text=
"d
03.02.2021
'3 Feb 2021'
13/3/2021
13-3-2020")

df %>% mutate(date=parsedate::parse_date(d))
##           d       date
##1 03.02.2021 2021-02-03
##2 3 Feb 2021 2021-02-03
##3  13/3/2021 2021-03-13
##4  13-3-2020 2020-03-13

A: Similar (but expanded) to Roland's suggestion, my answer here (in the (2) section) suggests a way to deal with multiple candidate formats.
## sample data
x <- c("03.02.2021", "3 Feb 2021")

formats <- c("%d.%m.%Y", "%d %b %Y")
dates <- as.Date(rep(NA, length(x)))
for (fmt in formats) {
  nas <- is.na(dates)
  dates[nas] <- as.Date(x[nas], format=fmt)
}
dates
# [1] "2021-02-03" "2021-02-03"

It is better to have the most-frequent format first in the formats vector. One could add a quick-escape to the loop if there are many formats, such as
for (fmt in formats) {
  nas <- is.na(dates)
  if (!any(nas)) break
  dates[nas] <- as.Date(x[nas], format=fmt)
}

but I suspect that it really won't be very beneficial unless both formats and x are rather large (I have no sizes in mind to quantify "large").

A: did you try lubridate ?
df <-read.table(header=TRUE,text=
                  "d
03.02.2021
'3 Feb 2021'
13/3/2021
13-3-2020")

dmy(df$d)

[1] "2021-02-03" "2021-02-03" "2021-03-13" "2020-03-13"

A: Using anydate
library(anytime)
addFormats(c("%d/m/%Y", '%d-%m-%Y') )
anydate(df$d)
[1] "2021-02-03" "2021-02-03" "2021-03-13" "2020-03-13"


text:
Q: Is a two dimensional rotationally symmetric probability density function equivalent to a radial one dimensional density function?? Assume that $f(x,y)$ is a two dimensional rotationally symmetric p.d.f.,  $f(x,y)=\tilde{f}(\sqrt{x^2+y^2})$. In the polar coordinates, $x=r \cos\varphi$, $y=r\sin\varphi$, we can average out the azimuthal angle to find a one dimensional radial p.d.f as follows,
$$ p(r)= r\int_{0}^{2\pi}d\varphi\, \tilde{f}(r)=2\pi r\, \tilde{f}(r).\qquad\qquad\qquad \qquad     (1)$$
The generating function of the distribution $f(x,y)$ is written as $\mathbb{E}[e^{i\mathbf{k}\cdot \mathbf{x}}]$ where $\mathbf{x}=(x,y)$ and $\mathbf{k}=(k_x,k_y)$ are two dimensional vectors. Here $\mathbb{E}[\cdots]=\int dx dy \cdots \,f(x,y)$. Then the generating function for a rotationally symmetric distribution is given by
$$  \mathbb{E}[e^{i\mathbf{k}\cdot \mathbf{x}}]=\int_{0}^{\infty}\int_{0}^{2\pi}r dr d\varphi\,e^{i k r \cos(\varphi-\varphi_k)}\tilde{f}(r)=2\pi\int_{0}^{\infty}r dr\, \tilde{f}(r)\,J_0(kr)=\int_0^{\infty} dr\, p(r) J_0(k r), $$
where in the above $k=\sqrt{k_x^2+k_y^2}$ and $\varphi_k=\text{atan2}(k_x,k_y)$ and $J_0(x)$ is the modified Bessel-Function of the first kind. If I define the averaging with respect to $p(r)$ as $\tilde{\mathbb{E}}[\cdots]=\int_0^{\infty} dr\cdots p(r)$ then we have the following:
$$ \mathbb{E}[e^{i\mathbf{k}\cdot \mathbf{x}}] \equiv \tilde{\mathbb{E}}[J_0(k r)]=1-\frac{1}{4}k^2\tilde{\mathbb{E}}[r^2]+\frac{1}{64}k^4\tilde{\mathbb{E}}[r^4]+\cdots\,.$$
Question: Based on the above, the characteristic function of a 2D rotationally symmetric p.d.f. can be obtained only from even moments ( $\tilde{\mathbb{E}}[r^{2k}]$) of the p.d.f. $p(r)$ which is defined in the range $[0,\infty)$. On the other hand, the characteristic function of $p(r)$ can be written as  $\tilde{\mathbb{E}}[e^{i t r}]$ where $t\in(-\infty,\infty)$(What is the characteristic function of a p.d.f with $\mathbb{R}^+$ support?). It simply means that  $\tilde{\mathbb{E}}[r^{2k+1}]$ are moments of $p(r)$ too. Now I am a bit confused. If I know all $\tilde{\mathbb{E}}[r^{2k}]$ then I know $f(x,y)$. However, in order to know $p(r)$ I should know about $\tilde{\mathbb{E}}[r^{k}]$ for odd $k$  as well as even $k$. On the other hand, $f(x,y)$ and $p(r)$ are uniquelly related to each other from equation (1).
My Guess: I think I am missing something obvious! My guess is that $p(r)$ and rotatinaly symmetric $f(x,y)$ are not equivalent, and I can use them interchangeably if I replace the characteristic function  $\tilde{\mathbb{E}}[e^{i t r}]$ to  $\tilde{\mathbb{E}}[J_0(k r)]$ for $p(r)$.


text:
Q: Where does Eclipse get list up update sites from? Yesterday I installed Eclipse 3.7.2 (Indigo) and I'm trying to configure it.   This is the 32 bit version on a 32 bit Ubuntu system.  When I do a "Check for Updates" it returns the following error:
'Contacting Software Sites' has encountered a problem.
Unable to read repository at http:/android/eclipse/content.xml.
Host name may not be null
Note the single slash after "http:"
Where does it get this URL from and how do I fix it?   . . . N.B. this URL is not in the Available Software Sites section of Install/Update under Preferences.
Thanks in advance.

A: Go to [Help] > [Install New Software...] > [Available Software Sites] and edit the bad url there.


text:
Q: why assign a different function for descriptor.value when use typescript decorator I'm new to Typescript and really get confused with the use of decorator. I saw some code as below:
function log(target: any, key: string, descriptor: any) {
    const original = descriptor.value;
    descriptor.value = function (...args: any[]) {
        // Call the original method
        const result = original.apply(this, args);
        // Log the call, and the result
        console.log(`${key} with args ${JSON.stringify(args)} returned ${JSON.stringify(result)}`);
        // Return the result
        return result;
    }
    return descriptor;
}

class Calculator {
    // Using the decorator
    @log
    square(num: number) {
        return num * num;
    }
}

const calculator = new Calculator();
// square with args [2] returned 4
calculator.square(2);

below is my questions:
Q1- I understand that descriptor.value contains the original square method, then  another anonymous function is assigned to descriptor.value, then return descriptor, I am not sure what exact it mean, but I guess the new function that descriptor.value contains will get called, but by whom? who will call the decorator log function and get the returned descriptor and call its value function?/Who is going to call log function?
Q2- why the new assigned anonymous function takes a array of parameter, isn't that a single parameter is enough as below:
...
descriptor.value = function (args: any) {
   ...
}

Q3- If I don't assign a different function to descriptor.value as:
function log(target: any, key: string, descriptor: any) {
    const original = descriptor.value; //does nothing
    return descriptor;
}

I assume the square method will be called twice, but it just get called once. So how come when you assign descriptor.value to a new different function then the new function will get called, which is inconsistent?


text:
Q: .htaccess rewrite 301 rules not working I am in the process of simplifying my URLs and have come up with a problem concerning the use of Rewrite in htaccess files.
Search engines currently list my pages in the following format
www.example.com/x/x/article_a/1159/
which is currently rewritten by the following htaccess file placed in the /x/x directory
RewriteRule walk_a/(.*)/$ /x/x/article_a.php?id=$1

This has worked fine for many years.
I want to simplify the URL to
www.example.com/article-1159-introduction
I have tried the following redirects placed in the root
RewriteRule ^x/x/article_a/(.*)/$ http://www.example.com/article-$1-introduction [R=301,NC,L]
RewriteRule ^article-(.*)-introduction$ /x/x/article_a.php?id=$1

The 301 rewrite seems to have no effect although the second rewrite command works fine.
What am I doing wrong?

A: Inside /x/x/.htaccess directory use this rule:
RewriteEngine On

RewriteRule ^article_a/(.*)/$ /article-$1-introduction [R=301,NC,L,NE]

Then inside root .htaccess have this rule:
RewriteEngine On

RewriteRule ^article-(.+)-introduction$ /x/x/article_a.php?id=$1 [L,QSA]


text:
Q: Magento add an postDispatch to a post action I have this controller :
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{

public function preDispatch()
{
    parent::preDispatch();

    if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
        $this->norouteAction();
    }
}

public function indexAction()
{
    $this->_initLayoutMessages('juron/ses');
    $this->renderLayout();
}

public function postAction()
{
    $post = $this->getRequest()->getPost();
    if ( $post ) {
        ......
    }
 }
}

In the /Mage/Contacts/etc/config.yml :
<events>
        <controller_action_postdispatch_contacts_post_action>
            <observers>
                <contacts>
                    <type>model</type>
                    <class>contacts/observer</class>
                    <method>postDispatch</method>
                <contacts>
            </observers>
        </controller_action_postdispatch_contacts_post_action>
    </events>

And in /Mage/Contacts/Model/Observer.php :
class Mage_Contacts_Model_Observer
{
    public function postDispatch(Varien_Event_Observer $observer)
    {
        echo 'Stop';
        die();
    }
}

Normally when I try to submit the contact form I shoul see Stop and the execution should be finished but not work like this. Seems the observer is not called. Can you help me please ? Thx in advance.

A: The right event to listen to here would be controller_action_postdispatch_contacts_index_post.
The structure is controller_action_postdispatch_ROUTER_CONTROLLERNAME_ACTIONNAME.
P.S. : acknowledge that you should write your module in the local pool and not in the core.


text:
Q: MySQL DataSource in Spring Boot is not available in other Service/Control classes and throwing null pointer exception I am not an expert with Java and Springboot but I am building a QuartzScheduler application with JDBCStore in Spring Boot, I am using @Configuration, @Repository, @Service annotations for different classes in different packages, Structure has been given below.

The MySQL DataSource is available in Controller classes with @Autowired to DataSource (which is as Private) but where as if i try with the same Autowiring in other service classes, it is not working and it is throwing Null Pointer exception.
While the application loading, the DataSource is not available but later on when i am checking with @PostConstruct by printing the DataSource, it is showing up the HikariPool-1 DataSource.
Able to get the DataSource name in the SimpleCronScheduler through the RestController Get Method, Where as if i @Autowire the SimpleCronScheduler in TriggerListenerService, I cannot get the object and cannot use its Private methods like DataSource etc.
spring.datasource.url = jdbc:mysql://localhost/quartzscheduler?useSSL=false
spring.datasource.username = root
spring.datasource.password = password
spring.datasource.driverClassName= com.mysql.jdbc.Driver
spring.quartz.jdbc.initialize-schema=never
spring.jpa.show-sql=true
spring.datasource.tomcat.testOnBorrow=true
spring.datasource.tomcat.validationQuery=SELECT 1
spring.datasource.jmx-enabled=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5InnoDBDialect

DataSource is null in main() method.
The scope the DataSource is available in config and Controller packages but where as in services package, it is not reachable and Null.
I am really confused what i am missing here, please guide me if there is any programming concept i need to learn here to get the scope of the DataSource is available across the application, With the spring boot, it should be availbale by default but i am facing issue in which i am unable to use it as it is throwing Null Pointer Exception even after Auto configured.
Looking forward to hear your guidance and suggestions...
------main method file-----
package com.bsq.quartzscheduler;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@ComponentScan
@EnableScheduling
@SpringBootApplication
@EnableAutoConfiguration
public class QuartzSchedulerPocApplication {

    @Autowired
    static DataSource dataSource;

    public static void main(String[] args) {

        SpringApplication.run(QuartzSchedulerPocApplication.class, args);
        System.out.println(" ^^^^^^^^^^ DataSource Name: "+ dataSource);
    }
}

-----------------Controller file----------
package com.bsq.quartzscheduler.controllers;

import static org.quartz.CronScheduleBuilder.cronSchedule;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.impl.matchers.EverythingMatcher.allJobs;
import static org.quartz.impl.matchers.EverythingMatcher.allTriggers;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;

import com.bsq.quartzscheduler.services.JobsListenerService;
import com.bsq.quartzscheduler.services.SampleJob;
import com.bsq.quartzscheduler.services.SampleJob2;
import com.bsq.quartzscheduler.services.SampleJob3;
import com.bsq.quartzscheduler.services.TriggerListenerService;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Controller
public class SimpleCronScheduler  {

     private Logger logger = LoggerFactory.getLogger(getClass());

     @Autowired
     private JobsListenerService jobsListenerService;

     @Autowired
     private TriggerListenerService triggerListener;

     @Autowired
     private Scheduler sc;

     @Autowired
     private JdbcTemplate jdbcTemplate;

     @Autowired
     private DataSource dataSource;

     @PostConstruct
     public DataSource init() throws SchedulerException, IOException {
            //sc = this.initiate();
            logger.info("Hello from SimpleCronScheduler Controller... and DataSource is: "+ dataSource); //Outputs as HikariPool-1
            return dataSource;
     }

     public void insertRecord() {
         System.out.println(">>>>>>>DataSource : " + dataSource + "JDBC TEmplate: "+ jdbcTemplate);
         String sql = "insert into qrtz_logtable (jobName, instance, createTime) values('BSQJ1', 'ANCE1','TIME')";
         try {
             System.out.println(">>>>>>>TRYING TO EXECUTE in insertRecord : " );
             jdbcTemplate.update(sql);

         } catch (Exception e) {
             System.out.println(">>>>>>>exception in insertRecord : " + e.getLocalizedMessage());

         }
     }

     @Bean
     public Scheduler getScheduler() {
         if ( sc == null ) {
             try {
                sc =  StdSchedulerFactory.getDefaultScheduler();
                sc.getListenerManager().addTriggerListener(triggerListener, allTriggers());
                sc.getListenerManager().addJobListener(jobsListenerService, allJobs());
                logger.info("Scheduler Name in getScheduler "+ sc.getSchedulerName());
            } catch (SchedulerException e) {
                logger.info("Exception in getScheduler method "+ e.getLocalizedMessage());
            }
         }
         return sc;
     }

    @Bean
    public String testMethod()  {
        logger.info( "Test Method Started "+dataSource);
        return "TMS and DatSource Name--- "+dataSource; // Outputs as HikariPool-1 when i make a get call from RestController to this method.
     }

     public String startScheduler(Scheduler sc) {
         try {
            sc = getScheduler();

            sc.start();
            logger.info( "Scheduler name "+ sc.getSchedulerName()+" Started ");
            return "Scheduler name "+ sc.getSchedulerName()+" Started ";
         } catch (SchedulerException e) {
            System.out.println("Start Scheduler exception "+ e.getMessage());
            logger.info("EXCEPTION in Start Schduler "+ e.getMessage());
            return "Failed to start Scheduler name "+ e.getMessage();
         }
      }

     public String stopScheduler(){
         try {
             sc = getScheduler();
             logger.info("Stopping Scheduler: "+ sc.getSchedulerName());
             sc.standby();
             logger.info("Keeping the scheduler in Standby "+ sc.getSchedulerName() );
             return "Keeping the scheduler in Standby "+ sc.getSchedulerName();
         } catch (SchedulerException  e ) {
             System.out.println("EXCEPTINO IN STOP SCHEDULER: "+ e.getMessage());
             logger.info("EXCEPTION in stop Schduler "+ e.getMessage());
             return "failed to Stop the the scheduler  "+e.getMessage();
         }
     }

     //Using CronTrigger to schedule the jobs
     public String scheduleJobs(String jobName, int jobNum, String cronExpression, String groupName, String triggerName)  {
         System.out.println("Entered into Schedule Jobs");
         JobDetail job = null;
         CronTrigger trigger = null;
         try {
             sc = getScheduler();

             if(jobNum==1) {
                 job = newJob(SampleJob.class).withIdentity(jobName, groupName).build();
             } else if(jobNum ==2 ) {
                 job = newJob(SampleJob2.class).withIdentity(jobName, groupName).build();
             } else {
                 job = newJob(SampleJob3.class).withIdentity(jobName, groupName).build();
             }
            // job = newJob(jobClass).withIdentity(jobName, groupName).build();
             trigger = newTrigger().withIdentity(triggerName, groupName).withSchedule(cronSchedule(cronExpression)).build();
             sc.getListenerManager().addTriggerListener(triggerListener, allTriggers());
             sc.getListenerManager().addJobListener(jobsListenerService, allJobs());
             sc.scheduleJob(job, trigger);
             logger.info(job.getKey() + " has been scheduled to run at: "  + " and repeat based on expression: "+ trigger.getCronExpression());
             return "Job Added and scheduled for "+ jobName;
        } catch (SchedulerException e) {
            System.out.println("Failed to get Scheduler"+e.getMessage());
            logger.info("Failed to get Scheduler "+ e.getMessage());
            return "Failed to add JOb "+ e.getMessage();
        }
             }

     public String runJob(String group, String jobName)    {
         try {
             sc = getScheduler();
             sc.triggerJob(new JobKey(jobName, group));
             logger.info("Running the Job rightaway  "+ group+"-"+jobName);
             return "Triggered the Job to run now "+  group+"-"+jobName;
         } catch (SchedulerException  e ) {
             System.out.println("EXCEPTINO IN RUN JOB : "+ e.getMessage());
             logger.info("EXCEPTION in RUN JOB "+ e.getMessage());
             return "Failed to run the job"+e.getMessage();
         }
     }

     public String stopJob(String group, String jobName)    {
         try {
             sc = getScheduler();
             sc.interrupt(new JobKey(jobName, group));
             logger.info("Stopping the Job rightaway  "+ group+"-"+jobName);
             return "Triggered the Job to run now "+  group+"-"+jobName;
         } catch (SchedulerException  e ) {
             System.out.println("EXCEPTINO IN INTERRUPTION OF JOB : "+ e.getMessage());
             logger.info("EXCEPTION INTERRUPTION OF JOB JOB "+ e.getMessage());
             return "Failed to STOP the job"+e.getMessage();
         }
     }

     public String deleteJob(String group, String name) {
         try {
             sc = getScheduler();
             sc.deleteJob(new JobKey(name, group));
             return "Job Deleted: "+  group+"-"+name;
         } catch (SchedulerException e) {
             return "Failed to Delete JOB: "+  group+"-"+name+ "Error is "+e.getMessage();
         }
     }

     public String deleteAllJobs() throws SchedulerException {
         sc = getScheduler();
         for (String groupName : sc.getJobGroupNames()) {
             for (JobKey jobKey : sc.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
                 sc.deleteJob(jobKey);
             }
         }
         return "All Jobs Deleted: ";
     }

}

-------------------Service file----------- where i am unable to access the dataSource.
package com.bsq.quartzscheduler.services;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.Trigger.CompletedExecutionInstruction;
import org.quartz.TriggerListener;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bsq.quartzscheduler.controllers.SimpleCronScheduler;

@Service
public class TriggerListenerService implements TriggerListener {

    private final Log logger = LogFactory.getLog(getClass());
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Autowired
    private SimpleCronScheduler scs;

    @Autowired
    private DataSource dataSource;

    @Override
    public String getName() {
        return "Main Trigger(IP) Listener";
    }

    @Override
    public void triggerComplete(Trigger trigger, JobExecutionContext context,
            CompletedExecutionInstruction triggerInstructionCode) {
        // do something with the event
        Date date = new Date();

        logger.info("Trigger Listerner###: Method: triggerComplete | Time: "+ dateFormat.format(date) +" | Job Name: " + context.getJobDetail().getKey().getName());
    }

    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext context) {
        // do something with the event
        Date date = new Date();

        String sql = "insert into qrtz_logtable (jobName, instance, createTime) values("+context.getJobDetail().getKey().getName()+", "+context.getJobInstance()+","+dateFormat.format(date)+")";

        System.out.println("DataSource in tListerner "+dataSource); //Outputs as NULL

        try{
            scs.insertRecord();
        } catch (Exception e) {
            System.out.println("ERROR MESSAGE OF SCS: "+e.getMessage()); //Outputs as NULL
        }

        logger.info("Trigger Listerner###: Method: triggerFired | Time: "+ dateFormat.format(date) +" | Job Name: " + context.getJobDetail().getKey().getName());

    }
    @Override
    public void triggerMisfired(Trigger trigger) {
        // do something with the event
        String jName;
        Date date = new Date();
        try {
            Scheduler sc = StdSchedulerFactory.getDefaultScheduler();
            sc.getContext();
            jName = sc.getJobDetail(trigger.getJobKey()).getKey().getName();

            logger.info("Trigger Listerner###: Method: triggerMisfired | Time: "+ dateFormat.format(date) +" | Job Name: " + jName);

        } catch (SchedulerException e) {
            System.out.println("Exception in triggerMisfired " +e.getMessage());
        }

        System.out.println("Trigger Listener###: Method:  triggerMisfired | Time:"+ dateFormat.format(date) +" | Job Name: " + trigger.getKey());

    }
    @Override
    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
        // do something with the event
        boolean veto = false;
        Date date = new Date();
        logger.info("Trigger Listerner###: Method: vetoJobExecution | Time: "+ dateFormat.format(date) +" | Job Name: " + context.getJobDetail().getKey().getName());

        return veto;
    }

}

A: I think this can happen when you declare the Datasource type wrongly.
Please check the Datasource class type.
the Datasource should be declared as a standard JDBC DataSource (i.e. javax.sql.DataSource).
import javax.sql.DataSource;
....
@Autowired
DataSource dataSource;


text:
Q: Restangular running onFulfilled callback on promise even when promise is rejected I'm moving my subject data to a service and trying to smart about the code but I'm running into some issues.
When I turn off my API server and run the create function, I expect just the onRejected callback to be fired. Rather both the onFulfilled and the onRejected callbacks are being fired.
Service
(function(){
  'use strict';

  angular
  .module('app')
  .factory('$cmSubjectData', $cmSubjectData);

  function $cmSubjectData($log, Restangular, $mdToast) {

    var service = {
      getAll: getAll,
      getById: getById,
      update: update,
      create: create,
      destroy: destroy
    };

    return service;

    function getAll() {
      return subjects().getList().then(handleSuccess, handleError('Error getting all subjects'));
    }

    function getById(id) {
      return subjects().one(id).get().then(handleSuccess, handleError('Error getting this subject'));
    }

    function update(subject) {
      Restangular.all('subjects')
      .post(subject)
      .then(handleSuccess, handleError('Error updating subject'));
    }

    function create(subject) {
      Restangular.all('subjects')
      .post(subject)
      .then(successToast(subject.basicInfo.firstName + ' has been created'), handleError('Error creating subject'));
    }

    function destroy(id) {
      var subject = subjects().one(id);
      subject.remove()
      .then(successToast('Subject has been deleted!'), handleError('There was an error deleting this subject'));
    }

    // Private Functions
    function subjects() {
      return Restangular.service('subjects');
    }

    function handleSuccess(data) {
      $log.info('Success');
      return data;
    }

    function handleError(error) {
      return function () {
        $log.warn(error);
      };
    }

    function successToast(content) {
      $mdToast.show(
        $mdToast.simple()
        .content(content)
      );
    }

  }

})();

Controller
(function() {
  'use strict';

  angular
  .module('app')
  .controller('SubjectNewCtrl', SubjectNewCtrl);

  function SubjectNewCtrl($cmSubjectData) {

    var vm = this;

    vm.subject = {};
    vm.createSubject = $cmSubjectData.create;

  }

})();

View where function is called:
<button ng-click="vm.createSubject(vm.subject)">Add</button>

Any help would be appreciated.

A: When you do
.then(successToast(...))

you are running successToast(...) immediately and passing the return value from that to .then() which is not the timing you want. Remember, you have to pass a function reference to .then() if you want it executed later.  If you include the parens () with your function, then that tells Javascript to execute your function immediately.  That is not what you want in this case.  If you had no extra arguments to the function, you could just do:
.then(successToast)

But, because you have arguments you want to pass when you call it, you can't do it that way.  So, you have two choices.  You can make it work like handleError() where calling it with the arguments just returns a function (so that is what gets passed to .then() like this:
function successToast(content) {
  return function() {
      $mdToast.show($mdToast.simple().content(content));
  }
}

Then, it gets call like you have already:
.then(successToast(subject.basicInfo.firstName + ' has been created'))

Or you can insert your own stub function reference in the call itself:
.then(function() {
    return successToast(subject.basicInfo.firstName + ' has been created');
});

Either example passes a function reference to .then() and does not execute the core of your logic until later when .then() calls that function reference.


text:
Q: Can a photon that is emitted from a denser part of the universe to a less dense part appear redshifted? Galaxy one is located in a dense area of the universe and galaxy two is located in a less dense part of the universe. Would galaxy one appear red-shifted to galaxy two?  Is the mass density at our position in the universe less dense than most other positions?

A: The answer to your question is yes, but the gravitational redshift could not be confused with cosmological redshift because it is small.
The basics of gravitational redshift can be grasped by the simple approximation that the redshift is given by
$$z \simeq \Delta \Phi /c^2,$$
where $\Delta \Phi$ is the difference in gravitational potential between where the photon was emitted and where it is absorbed/detected. This approximation is valid, where the ratio of gravitational potential energy to rest mass energy is small - so practically all circumstances except near black holes and neutron stars.
What this means is that if a photon is emitted from deep inside a potential well and then is detected higher in a potential well, a positive $z$ or redshift would be observed. If you reverse the experiment, then a blue shift would result.
If a photon travels into a galaxy, through it and then out the other side, there is no net redshift (unless the gravitational potential somehow changes whilst the photon is travelling, which is actually the Sachs-Wolfe effect referred to byJohn Rennie).
Now, coming to your scenario. You are specifying that the photons are emitted in a deep potential well, then detected in a shallower potential well. This results in a positive $\Delta \Phi$ and a net redshift. However, as the photon travels across the universe it is affected by the expansion and gets further redshifted. Some orders of magnitude would be helpful:
Suppose a galaxy is in a dense, spherically symmetric cluster, with $10^{14}$ solar masses interior to it, and at a distance from the centre of $\sim 1$ Mpc. If $\Phi \sim GM/r$, then a photon emitted by the galaxy will have an observed redshift at infinity of $GM/r c^2 = 5\times 10^{-6}$, equivalent to an apparent recession velocity of only 1.5 km/s. Meanwhile, the apparent recession velocity due to the expansion of the universe is $H_0 d$, where $H_0 = 70$ km s$^{-1}$/Mpc and $d$ is the distance in Mpc. Thus, even if the cluster of galaxies was only a fraction of a Mpc away (like the Andromeda galaxy), the gravitational redshift would be completely swamped by the redshift due to the expansion of the universe. In addition, we have not subtracted the blue shift caused by the photons falling into the gravitational potential of our own Galaxy (maybe 0.1 km/s) or the fact that galaxies have peculiar motions within a cluster that are of order hundreds of km/s!
The Milky Way is not in a particularly dense part of the universe. The local group is quite sparse, and we are about 20 Mpc from the nearest dense cluster (Virgo).

A: Yes, you're quite correct that galaxies in a region of the universe with greater than average density would appear redshifted to observers outside that region.
In fact this is the origin of the Sachs-Wolfe effect, which is an important way that we study various properties of the universe.
Actually doing the calculation is hard because of course the universe is expanding and the rate of expansion changes with time. We need to take this into account and make sure that we exclude the cosmlogical red shift from our calculation. However almost everywhere in the universe the gravitational fields are weak enough that we can use an approximation called the weak field limit.
One of the ideas that physics students get taught early on is gravitational potential energy. You have probably been taught that for small distances it's:
$$ \text{PE} = mgh $$
though in GR we're normally interested in the potential energy per unit mass i.e. we set $m=1$ to get:
$$ \Delta \Phi = gh $$
And for large distances from a spherical body it's given by Newton's equation:
$$ \Delta \Phi = -\frac{GM}{r} $$
This also applies to galaxies though the equations get more complicated, and it also applies to groups of galaxies and galaxy clusters. In fact measuring the potential energy of galaxy clusters was how Fritz Zwicky first discovered the existence of dark matter.
The point of all this is that in the weak field limit the difference in gravitational potential between two places is directly related to the difference in the time dilation between those places by:
$$ \frac{d\tau_a}{d\tau_b} = \sqrt{1 - \frac{2\Delta \Phi}{c^2}} \tag{1} $$
So if you calculate the difference in the potential energy between the overdense region and the underdense region and feed it into equation (1) then it will give you the relative time dilation. Since in general $\Delta U$ will not be zero that means in general this is a difference in the time dilation and one galaxy will appear red shifted relative to the other. The reverse is of course also true - one galaxy will appear blue shifted relative to the other.
Lastly you ask:

Is the mass density at our position in the universe less dense than most other positions?

And the answer is that we seem to be about average. We're in the outer edges of the Virgo galaxy cluster, so we're neither in the overdense region at the centre of a cluster nor in the underdense region in a void.

A:
Can a photon that is emitted from a denser part of the universe to a less dense part be redshifted?

I'm not quite clear what you're asking, but I'll say no. One example of a photon moving from a denser part of the universe to a less dense part is gravitational redshift, which is also called Einstein shift. But people who don't understand relativity often get this wrong. See what Einstein said:
"An atom absorbs or emits light at a frequency which is dependent on the potential of the gravitational field in which it is situated".
The photon is emitted at a lower frequency when it's lower down. It is emitted already redshifted. It doesn't get redshifted as it ascends. In similar vein an intergalactic photon doesn't reduce in frequency when it moves to a less-dense part of the universe.

Galaxy one is located in a dense area of the universe and galaxy two is located in a less dense part of the universe. Would galaxy one appear red-shifted to galaxy two?

Yes it would. Because photons in that denser region are emitted at a lower frequency than in less-dense regions.

Is the mass density at our position in the universe less dense than most other positions?

Not as far as I know. If it was, we might expect to see the same redshift for galaxies at different distances. We don't, we see redshift increasing with distance, in line with an expanding universe. By the by, my understanding of general relativity tells me that space just has to expand. It can't contract, or stay in a steady state. The mystery of course is why Einstein didn't predict an expanding universe.


text:
Q: Powershell get directory name I want a code snippet to put into my profile that will always select the most recent folder.
(gci C:\Users\$env:username\Documents\releases | ? { $_.PSIsContainer } | sort CreationTime | Select-Object Name)[-1]

This is my output.
Name
----
20201116_124047

I would like the output to be a string that I can place into a variable. I am on Powershell 5.1
20201116_124047

A: try this :
$myvar=Get-ChildItem "C:\Users\$env:username\Documents\releases" -Directory | sort CreationTime -Descending | Select -ExpandProperty Name -First 1

A: The property I think you need is LastWriteTime, instead of CreationTime.
Also, unless you are using a PowerShell version below 3.0, you can use the -Directory switch and do not have to use Where-Object { $_.PSIsContainer }
Get-ChildItem -Path "C:\Users\$env:username\Documents\releases" -Directory |
Sort-Object LastWriteTime |
Select-Object -ExpandProperty Name -Last 1