text:
Q: C++ SimpleVector Using Templates I am trying to get my program to let the user choose which data type they would like to use, 1 for int, 2 for double, and 3 for string. Take that type and make it the type for our dynamic array. Allow the user to say how many inputs of the data they would like, and then allow the user to enter the data.
For some reason not clear to me, my program crashes right after the user enters any number for the type they want to use.
(I also have some other methods to implement, but I wanted to get this fixed first. So that's why there are unused methods.)
Is there something I am not seeing here? Any help is greatly appreciated. Thank you so much.
#include <iostream>
#include <cstdlib>

using namespace std;

template <class T>
class SimpleVector
{
private:
    T *tempPointer;
    int lengthOfArray;

public:
    SimpleVector();
    ~SimpleVector();
    SimpleVector(int lengthOfArray);
    SimpleVector(const SimpleVector& copy);
    int getArraySize();
    T getElementAt(int n);
    T & operator[](int index);
};

// default no-arg constructor
template <class T>
SimpleVector<T>::SimpleVector()
{
    tempPointer = NULL;
    lengthOfArray = 0;
}

// destructor for deallocating memory
template <class T>
SimpleVector<T>::~SimpleVector()
{
    delete [] tempPointer;
}

// single argument constructor
template <class T>
SimpleVector<T>::SimpleVector(int dynamicArray)
{
    lengthOfArray = dynamicArray;
    tempPointer = new T[lengthOfArray];
}

// Copy constructor
template <class T>
SimpleVector<T>::SimpleVector(const SimpleVector& copy)
: lengthOfArray(copy.lengthOfArray), tempPointer(new int[copy.lengthOfArray])
{
    int newSize = copy->size();
    tempPointer = new T[newSize];

    for(int i = 0; i < newSize; i++){
        tempPointer[i] = copy.tempPointer[i];
    }
}

// gets the size of the dynamic array
template <class T>
int SimpleVector<T>::getArraySize()
{
    return lengthOfArray;
}

// returns element from array at specified position
template <class T>
T SimpleVector<T>::getElementAt(int n)
{
    return *(tempPointer + n);
}

// returns reference to the element in array indexed by subscript
template <class T>
T & SimpleVector<T>::operator[](int index)
{
    return this->tempPointer[index];
}

int main()
{
    int dataType;
    int dataSize = 0;
    char keepGoing;

    do{
        cout << "What type of data do you want to enter?\n(1 for integer, 2 for double and 3 for strings)" << endl;
        cin >> dataType;
        cout << "How many data inputs? " << endl;
        cin >> dataSize;

        SimpleVector <int> list1(dataSize);
        if (dataType == 1) {
            SimpleVector <int> list1(dataSize);
        }
        else if (dataType == 2) {
            SimpleVector <double> list1(dataSize);
        }
        else if (dataType == 3) {
            SimpleVector <string> list1(dataSize);
        }
        else {
            cout << " That's not an available option. Bye! " << endl;
            return 0;
        }

        cout << "Please enter the data:" << endl;
        for (int i = 0; i <= dataSize; i++) {
            cin >> list1[i];
        }

        cout << "Do you want to enter data again? (y/n?)" << endl;
        cin >> keepGoing;
    }while((keepGoing == 'Y') | (keepGoing == 'y'));
    return 0;
}

A:
For some reason not clear to me, my program crashes right after the user enters any number for the type they want to use.

I would suggest, that you test your program multiple times, when you are writing it. As @Jarod42 said in his comment, your if statements don't really do much, because your
SimpleVector <type> list1(dataSize);

gets destroyed after { }.
So basically whatever number user types, your SimpleVector will always be of the type int.

Now when you try to:
cout << "Please enter the data:" << endl;
for (int i = 0; i <= dataSize; i++) {
cin >> list1[i];
}

you are calling function:
template <class T>
T & SimpleVector<T>::operator[](int index)
{
    return this->tempPointer[index];
}

At this point, you pointer is pointing to NULL, but you are trying to access [index] of your pointer, which is pointing to NULL. That's why you program crashes.
EDIT:
I'm not sure if this is what you want, but i'll give it a try :
do{
    cout << "What type of data do you want to enter?\n(1 for integer, 2 for double and 3 for strings)" << endl;
    cin >> dataType;

    cout << "How many data inputs? " << endl;
    cin >> dataSize;

    if (dataType == 1) {
        SimpleVector <int> list1(dataSize);
        cout << "Please enter the data:" << endl;
        for (int i = 0; i <= dataSize; i++) {
            cin >> list1[i];
        }
    }
    else if (dataType == 2) {
        SimpleVector <double> list1(dataSize);
        cout << "Please enter the data:" << endl;
        for (int i = 0; i <= dataSize; i++) {
            cin >> list1[i];
        }
    }
    else if (dataType == 3) {
        SimpleVector <string> list1(dataSize);
        cout << "Please enter the data:" << endl;
        for (int i = 0; i <= dataSize; i++) {
            cin >> list1[i];
        }
    }
    else {
        cout << " That's not an available option. Bye! " << endl;
        return 0;
    }

    cout << "Do you want to enter data again? (y/n?)" << endl;
    cin >> keepGoing;
}while((keepGoing == 'Y') | (keepGoing == 'y'));


text:
Q: porting and backing up databases I am using sqlite3 in development and mysql in production on a Rails 3.2 app.
I'd like to be able to backup the mysql, and also to create a sqlite copy of it for use in the development environment. Anyone know how to do this, or the preferred way to back up mysql at least?

A: I'm partial to this one, and use it to convert to/from MSSQL, sqlite and MySQL quite a lot:
https://github.com/unixmonkey/rails_db_convert_using_adapters

A: This may not be feasible if you have a large DB, but I am working with a rather small one (about 10MB).
(1) I back up all of my model classes into a .zip file using a rake task, and then
(2) have a button (with admin authentication) that runs another rake task to reload the data.
So I can backup the data in dev/prod mode, push my files to the other environment, and reload the data from backup (it's in .csv files, so it's DB-independent). This worked for me switching between sqlite3 and mysql2 (I am using Rails 4.0.1 if that's relevant).
I can post code if that would be helpful to people, but it's a little messy so I'll save the eyesore unless someone would find it helpful. I've found the .csv into .zip file backup to be a nice workaround for different SQL systems, if you're working on the order of megabytes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a new property to Redux state when dispatching an action I have an initialState in my reducer which is bit of nested.I am trying to add a new property "isTouched" to my state when dispatching an action/state changes.
    const initialState = {
     isLoading: false,
     events: [
      { year:2021 , place: [{id:1,name:"BD"}] },
      { year: 2020, place: [{id:2,name:"AMS"}] },
    ],
  };

and in my reducer:
case types.TOGGLE_PLACE_INFO:
  return {
    ...state,
     here need to write the logic if events.place.id === action.payload then add a new property to
   "place" like this: place: [id:1,name:"BD",isTouched:true]
   }

so after that my state would looks like this:
   const initialState = {
     isLoading: false,
     events: [
      { year:2021 , place: [{id:1,name:"BD", isTouched:true}] },
      { year: 2020, place: [{id:2,name:"AMS"}] },
    ],
  };

Sandbox link: https://codesandbox.io/s/holy-tdd-v3gbd?file=/src/reducers/commonReducer.js
so, when the setTouched button is clicked it should update the place and add isTouched: true
Does anybody know any work around how to implement this logic. Any helps would be highly appreciated.Thanks in Advance.

A: as Dennis' says, your code isn't valid javascript. you want to store it in an object instead of an array
try something like this:
const initialState = {
     isLoading: false,
     events: [
      { year: 2021, place: [ {id:1, name:"BD"} ]},
      { year: 2020, place: [ {id:2, name:"AMS"} ]},
    ],
};

case types.TOGGLE_PLACE_INFO:
  return {
    ...state,
    events: state.events.map((event) =>
              event.id === action.payload.id
                 ? {...event, place: [{...event.place, isTouched:true}]}
                 : event
              )
          }

I've changed your initialState so place is now valid. im then mapping over all the values and if they match I return the current like so {...event} and then adding in the new isTouched key like so: {...event, isTouched: true}. then secondly if they don't match im just returning event
let me know if makes sense. can clarify if not!


text:
Q: Rails + Google Calendar Event Import I would really like to import events from my google calendar into my rails application. Right now, I'm not sure what the best way of doing that would be. I know that I can probably pull down the ics/xml file from my private calendar link and then somehow parse that but I was wondering if there was an easier way to go about doing this.
For reference, I did try to use the gcal4ruby gem and it kept throwing me the error:
        no such file to load -- gcal4ruby
I installed the gem using:
        sudo gem install gcal4ruby
I also tried to add it to my gemfile and then bundle install but that didn't have any effect.

A: You might want to look at GCal4Ruby and this demo app


text:
Q: Implementing a U-net for image segmentation and have the following error: NameError: name 'val_iou' is not defined I'm trying to use a U-net to apply image segmentation to the RUGD dataset.  I get the following error, I'm stuck.
       'lrs':lrs}

print('Total time: {:.2f}m' .format((time.time()-fit_time)/60))

return history

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-17-112aada9db24> in <module>
         98
         99         #iou
    --> 100 val_iou.append(val_iou_score/len(val_loader))
        101 train_iou.append(iou_score/len(train_loader))
        102 train_acc.append(accuracy/len(train_loader))

    NameError: name 'val_iou' is not defined

Installing segmentation-models for pytorch
!pip install -q segmentation-models-pytorch
!pip install -q torchsummary

Installing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms as T
import torchvision
import torch.nn.functional as F
from torch.autograd import Variable

from PIL import Image
import cv2
import albumentations as A

import os
import time
from tqdm.notebook import tqdm

from torchsummary import summary
import segmentation_models_pytorch as smp

device = torch.device("cpu" if torch.cuda.is_available() else "cpu")

Name and direct paths
IMAGE_PATH = '/data/users/mypath/Rugd_dataset/images/train/'
MASK_PATH = '/data/users/mypath/Rugd_dataset/mask/train/'

Create dataframe
n_classes = 24

def create_df():
    name = []
    for dirname, _, filenames in os.walk(IMAGE_PATH):
        for filename in filenames:
            name.append(filename.split('.')[0])
    return pd.DataFrame({'id': name}, index = np.arange(0, len(name)))

df = create_df()
print('Total Images: ',len(df))

Total Images:  7387
Split Test and Train
X_trainval, X_test = train_test_split(df['id'].values, test_size=0.1, random_state=19)
X_train, X_val = train_test_split(X_trainval, test_size=0.15, random_state=19)

print('Train Size : ', len(X_train))
print('Val Size : ', len(X_val))
print('Test Size : ', len(X_test))

# show original picture with overlay of mask

img = Image.open(IMAGE_PATH + df['id'][0] + '.png')
mask = Image.open(MASK_PATH + df['id'][0] + '.png')
print('Image size', np.asarray(img).shape)
print('Mask size', np.asarray(mask).shape)

plt.imshow(img)
plt.imshow(mask, alpha=0.6)
plt.title('Picture with Mask Applied')
plt.show()

Image size (550, 688, 3)
Mask size (550, 688, 3)
image rendered
Define U-net
class RugdDataset(Dataset):

    def __init__(self, img_path, mask_path, X, mean, std, transform=None, patch=False):
        self.img_path = img_path
        self.mask_path = mask_path
        self.X = X
        self.transform = transform
        self.patches = patch
        self.mean = mean
        self.std = std

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

    def __getitem__(self, idx):
        img = cv2.imread(self.img_path + self.X[idx] + '.png')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        mask = cv2.imread(self.mask_path + self.X[idx] + '.png', cv2.IMREAD_GRAYSCALE)

        if self.transform is not None:
            aug = self.transform(image=img, mask=mask)
            img = Image.fromarray(aug['image'])
            mask = aug['mask']

        if self.transform is None:
            img = Image.fromarray(img)

        t = T.Compose([T.ToTensor(), T.Normalize(self.mean, self.std)])
        img = t(img)
        mask = torch.from_numpy(mask).long()

        '''
        if self.patches:
            img, mask = self.tiles(img, mask)

        return img, mask
        '''
    '''
    def tiles(self, img, mask):
        img_patches = img.unfold(1, 512, 512).unfold(2, 768, 768)
        im_patches = img_patches.continuous().view(3, -1, 512, 768)
        img_patches = img_patches.permute(1,0,2,3)

        mask_patches = mask.unfold(0, 512, 512).unfold(1, 768, 768)
        mask_patches = mask_patches.contiguous().view(-1, 512, 768)

        return img_patches, mask_patches
    '''

Apply augmentation and initiate dataloader
mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]

t_train = A.Compose([A.Resize(512, 512, interpolation=cv2.INTER_NEAREST), A.HorizontalFlip(), A.VerticalFlip(),
                     A.GridDistortion(p=0.2), A.RandomBrightnessContrast((0,0.5),(0,0.5)), A.GaussNoise()])
t_val = A.Compose([A.Resize(512, 512, interpolation=cv2.INTER_NEAREST), A.HorizontalFlip(), A.GridDistortion(p=0.2)])

# dataset
train_set = RugdDataset(IMAGE_PATH, MASK_PATH, X_train, mean, std, t_train, patch=False)
val_set = RugdDataset(IMAGE_PATH, MASK_PATH, X_val, mean, std, t_val, patch=False)

# dataloader
batch_size = 3

train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=True)

build the model
model = smp.Unet('mobilenet_v2', encoder_weights='imagenet', classes=24, activation=None,
                 encoder_depth=5, decoder_channels=[256, 128, 64, 32, 16])

render the model
model

Def pixel accuracy

def pixel_accuracy(output, mask):
    with torch.no_grad():
        output = torch.argmax(F.softmax(output, dim=1), dim=1)
        correct = torch.eq(output, mask).int()
        accuracy = float(correct.sum()) / float(correct.numel())
    return accuracy

Define Miou
def mIoU(pred_mask, mask, smooth=1e-10, n_classes=24):
    with torch.no_grad():
        pred_mask = F.softmax(pred_mask, dim=1)
        pred_mask = torch.argmax(pred_mask, dim=1)
        pred_mask = pred_mask.contiguous().view(-1)
        mask = mask.contiguous().view(-1)

        iou_per_class = []
        for clas in range(0, n_classes): #loop per pixel class
            true_class = pred_mask == clas
            true_label = mask == clas

            if true_label.long().sum().item() == 0: # no exist label in this loop
                iou_per_class.append(np.nan)
            else:
                intersect = torch.logical_and(true_class, true_label).sum().float().item()
                union = torch.logical_or(true_class, true_label).sum().float().item()

                iou = (intersect + smooth) / (union + smooth)
                iou_per_class.append(iou)
        return np.nanmean(iou_per_class)

def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def fit(epochs, model, train_loader, val_loader, criterion, optimizer, scheduler, patch=False):
    torch.cuda.empty_cache()
    train_losses = []
    test_losses = []
    val_iou = []; val_acc = []
    train_iou = []; train_acc = []
    lrs = []
    min_loss = np.inf
    decrease = 1 ; not_improve=0

    model.to(device)
    fit_time = time.time()
    for e in range(epochs):
        since = time.time()
        running_loss = 0
        iou_score = 0
        accuracy = 0
        # training loop
        model.train()
        '''
        for i, data in enumerate(tqdm(train_loader)):
            # training phase
            image_tiles, mask_tiles = data
            if patch:
                bs, n_tiles, c, h, w = image_tiles.size()

                image_tiles = image_tiles.view(-1,c, h, w)
                mask_tiles = mask_tiles.view(-1, h, w)
        '''

        image = img.to(device); mask = mask.to(device);

            # forward
        output = model(image)
        loss = criterion(output, mask)
            # evaluation metrics
        iou_score += mIoU(output, mask)
        accuracy += pixel_accuracy(output, mask)
            # backward
        loss.backward()
        optimizer.step() #update weight
        optimizer.zero_grad() #reset gradient

            # step the learining rate
        lrs.append(get_lr(optimizer))
        scheduler.step()

        running_loss += loss.item()

    else:
        model.eval()
        test_loss = 0
        test_accuracy = 0
        val_iou_score = 0
        # validation loop
        with torch.no_grad():
            for i, data in enumerate(tqdm(val_loader)):
                # reshape to 9 patches
                image, mask = data

                if patch:
                    bs, n, c, h, w = image.size()

                    image = image.view(-1, c, h, w)
                    mask = mask.view(-1, h, w)

                image = img.to(device); mask = mask.to(device);
                output = model(image)
                # evaluation metrics
                val_iou_score += mIoU(output, mask)
                test_accuracy += pixel_accuracy(output, mask)
                # loss
                loss = criterion(output, mask)
                test_loss += loss.item()
                # calculate mean for each batch
            train_losses.append(running_loss/len(train_loader))
            test_losses.append(test_loss/len(val_loader))

            if min_loss > (test_loss/len(val_loader)):
                print('Loss Decreasing.. {:.3f} >> {:.3f} ' .format(min_loss, (test_loss/len(val_loader))))
                min_loss = (test_loss/len(val_loader))
                decrease += 1
                if decrease % 5 == 0:
                    print('saving model...')
                    torch.save(model, 'Unet-mobilnet_v2_mIoU-{:.3f}.pt'.format(val_iou_score/len(val_loader)))

            if (test_loss/len(val_loader)) > min_loss:
                not_improve += 1
                min_loss = (test_loss/len(val_loader))
                print(f'Loss Not Decrease for {not_improve} time')
                if not_improve == 7:
                    print('Loss not decrease for 7 times, Stop Training')
                    # break

#iou
val_iou.append(val_iou_score/len(val_loader))
train_iou.append(iou_score/len(train_loader))
train_acc.append(accuracy/len(train_loader))
val_acc.append(test_accuracy/len(val_loader))
print("Epoch:{}/{}".format(e+1, epochs),
      "Train Loss: {:.3f}..".format(running_loss/len(train_loader)),
      "Val Loss: {:.3f}..".format(test_loss/len(val_loader)),
      "Train mIoU:{:.3f}..".format(iou_score/len(train_loader)),
      "Val mIoU:{:.3f}..".format(val_iou_score/len(val_loader)),
      "Val ACC:{:.3f}..".format(test_accuracy/len(val_loader)),
      "Time: {:.2f}m".format((time.time()-since)/60))

history = {'train_loss' : train_losses, 'val_loss': test_losses,
           'train_miou' : train_iou, 'val_miou':val_iou,
           'train_acc' :train_acc, 'val_acc':val_acc,
           'lrs':lrs}
print('Total time: {:.2f}m' .format((time.time()-fit_time)/60))
return history

This the point where the model fails
         'lrs':lrs}

print('Total time: {:.2f}m' .format((time.time()-fit_time)/60))

return history

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-17-112aada9db24> in <module>
         98
         99         #iou
    --> 100 val_iou.append(val_iou_score/len(val_loader))
        101 train_iou.append(iou_score/len(train_loader))
        102 train_acc.append(accuracy/len(train_loader))

    NameError: name 'val_iou' is not defined

Remainder of the code
max_lr = 1e-3
epoch = 15
weight_decay = 1e-4

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=max_lr, weight_decay=weight_decay)
sched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epoch, steps_per_epoch=len(train_loader))

history = fit(epoch, model, train_loader, val_loader, criterion, optimizer, sched)


text:
Q: Type assert custom type to base type Is it possible to type assert a custom type to its base type?
For example, if I have the following
type A []interface{}

var x = map[string]interface{}{
        "hello":"a",
        "world":A{"b","c"},
    }

y := x["world"]

Then if I try to type assert via y.([]interface{}) I get the error //interface {} is A, not []interface {}.
Edit: As an answer below has noted, I can assert to type A via y.(A). The problem stems from x being given by a Mongo driver. Some drivers implement their own types, for example, the official mongo driver implements a bson.A type for []interface types. If I switch drivers then my type assertions need to change to match their custom types, which is something I want to avoid.

A: When type asserting (to) a concrete type, you can only type assert the same type that is stored in the interface value, not its base type. Of course when you have the concrete type, you can convert that to its base type.
You said you want to avoid that, you want to avoid having to refer to the concrete type.
To do that, you will need reflection. Obtain a reflect.Value descriptor of the value, and use the Value.Convert() method to "directly" convert to its base type, skipping the "actual" type. This will succeed because a value can be converted to a value of its base type.
Of course the Value.Convert() method will yield a value of type reflect.Value (and not []interface{}), but you can get the interface{} value wrapping this using Value.Interface(). You will now have an interface{} that wraps a concrete value of type []interface{}, from which you can now type assert a value of type []interface{}.
See this example:
z := reflect.ValueOf(y).Convert(reflect.TypeOf([]interface{}{})).
    Interface().([]interface{})

fmt.Printf("%T %v", z, z)

Output (try it on the Go Playground):
[]interface {} [b c]

There's a lot of boilerplate here, and this won't be nearly as efficient as a simple type-assertion and conversion. Try to avoid doing it this way.

A: You cannot type assert variable y to []interface{} because the actual data type of y is A (even though A is an alias of []interface{}).
Working example:
fmt.Println(y.(A))

But you can convert variable with A data type to []interface{} by using conversion. Example:
w := y.(A)
x := []interface{}(w)

// or

z := []interface{}(y.(A))


text:
Q: ¿Qué tiene más prioridad, un script al final del body o un script en un documento aparte? Si en un pagina web, dos sentencias están afectando al mismo elemento html y se contradicen, es decir, una da una orden con un valor y la otra la misma orden pero con otro valor, una ordena desde el body y la otra desde el documento .js... ¿cual tendria prioridad?

A: La prioridad la tendra el ultimo en ser declarado.
Ej: en este caso la accion no se realizará
<script type="text/javascript" src="js/hacerAlgo.js">

<script>
    function noHacerAlgo(){}
</script>

Ej: en este caso la accion SI se realizará
<script>
    function noHacerAlgo(){}
</script>

<script type="text/javascript" src="js/hacerAlgo.js">

A: El navegador lee el documento HTML de arriba hacia abajo, por tanto, cada hoja de estilos y/o script se ejecuta en orden descendente.
Digamos que tu documento HTML se ve asi:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="main.js"></script>
    <script type="text/javascript">
          var x = 15
          console.log(x)
    </script>
</body>
</html>

En este caso, la variable x siempre sera igual a 15; porque ese script es el ultimo en ser declarado, por ende, aunque en tu archivo externo main.js tengas otro valor y sea leido primero; al continuar leyendo el documento, al llegar al 2do script el valor cambia a 15 y este es el que termina ejecutandose.
Ahora, digamos que en tu HTML escribes el script antes de importar el archivo externo:
    <script type="text/javascript">
          var x = 15
    </script>
    <script src="main.js"></script>

Ahora, si tienes la misma funcion en main.js, es esta la que se termina ejecutando.
PARA ACLARAR: Si tienes un archivo externo, el navegador primero leera todo ese archivo antes de continuar al siguiente script; es por esto que no importa si tu archivo externo tiene 500 lineas y tu script en HTML tiene solo 5; el navegador primero leera las 500 lineas y luego seguira al otro script.
EDIT:
Observa este ejemplo; declare 3 scripts en el documento HTML; uno esta en la etiqueta head, y los otros dos al final de la etiqueta body;
Al correr el fragmento; puedes ver que siempre se imprime en consola el valor que tiene el ultimo script que dice var x = "Segundo Script en body" ya que el documento se empieza a leer de arriba hacia abajo, para el momento en que se llega a ejecutar el script que dice console.log(x), el ultimo valor de x que el navegador leyo es Segundo script en body; por tanto es ese ultimo el que se imprime, sin importar los valores anteriores.

var x = 60
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script type="text/javascript">
    var x = "Script en head"
  </script>
  <title>Document</title>
</head>

<body>

  <script type="text/javascript">
    var x = "Primer Script en body"
  </script>

  <script type="text/javascript">
    var x = "Segundo Script en body"
  </script>

  <script type="text/javascript">
    console.log(x)
  </script>
</body>


text:
Q: How to select contact number from contact list using android studio? Look at my screenshot
How do I get the selected contact's number & name from contact list.

A: onClick code
 Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
 pickContact.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE)
 startActivityForResult(pickContact, 1);

onActivityResult code
 Uri contactData = data.getData();
 Cursor c = getContentResolver().query(contactData, null, null, null, null);
 if (c.moveToFirst()) {
                   int phoneIndex = getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                   String num = c.getString(phoneIndex);
                   Toast.makeText(MainActivity.this, "Number=" + num, Toast.LENGTH_LONG).show();
           }

A: To get contact name, number as well as email also of a selected contact from your contact list, you just need to simply add this code.
private Button btn;
private String TAG = "Contacts";
private static final int RESULT_PICK_CONTACT = 1;

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectSingleContact();
    }
});

private void selectSingleContact() {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
    // Check for the request code, we might be usign multiple startActivityForResult
    switch (requestCode) {
        case RESULT_PICK_CONTACT:
            contactPicked(data);
            break;
    }
} else {
    Log.e("ContactFragment", "Failed to pick contact");
       }
}

private void contactPicked(Intent data) {

Uri uri = data.getData();
Log.i(TAG, "contactPicked() uri " + uri.toString());
Cursor cursor;
ContentResolver cr = getActivity().getContentResolver();

try {
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (null != cur && cur.getCount() > 0) {
        cur.moveToFirst();
        for (String column : cur.getColumnNames()) {
            Log.i(TAG, "contactPicked() Contacts column " + column + " : " + cur.getString(cur.getColumnIndex(column)));
        }
    }

    if (cur.getCount() > 0) {
      //Query the content uri
        cursor = getActivity().getContentResolver().query(uri, null, null, null, null);

        if (null != cursor && cursor.getCount() > 0) {
            cursor.moveToFirst();
            for (String column : cursor.getColumnNames()) {
                Log.i(TAG, "contactPicked() uri column " + column + " : " + cursor.getString(cursor.getColumnIndex(column)));
            }
        }

        cursor.moveToFirst();
        id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        Log.i(TAG, "contactPicked() uri id " + id);
        String contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        Log.i(TAG, "contactPicked() uri contact id " + contact_id);
        // column index of the contact name
        name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        // column index of the phone number
        phoneNo = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        //get Email id of selected contact....
        Log.e("ContactsFragment", "::>> " + id + name + phoneNo);

        Cursor cur1 = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contact_id}, null);

        if (null != cur1 && cur1.getCount() > 0) {
            cur1.moveToFirst();
            for (String column : cur1.getColumnNames()) {
                Log.i(TAG, "contactPicked() Email column " + column + " : " + cur1.getString(cur1.getColumnIndex(column)));
                email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            }

           //HERE YOU GET name, phoneno & email of selected contact from contactlist.....
            Log.e("setcontactDetails","::>>" + name+"\nPhoneno:" + phoneNo+"\nEmail: " + email);
        } else {
            Log.e("setcontactDetails","::>>" + name+"\nPhoneno:" + phoneNo+"\nEmail: " + email);
        }
    }
} catch (IndexOutOfBoundsException e) {
    e.printStackTrace();
    }
}

Also add permissions to your AndroidManifest.xml
It works for me, hope it will works for you also.

A: @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_usercontact);

    class MainActivity extends Activity {
        private final int REQUEST_CODE=99;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.content_usercontact);
            EditText editText = (EditText)findViewById(R.id.editTextcontacts1);
            EditText editText1 = (EditText)findViewById(R.id.editTextcontacts2);
            EditText editText2 = (EditText)findViewById(R.id.editTextcontacts3);
            editText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            });

            editText1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            });

            editText2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            });

        }

        @Override
        public void onActivityResult(int reqCode, int resultCode, Intent data) {
            super.onActivityResult(reqCode, resultCode, data);
            switch (reqCode) {
                case (REQUEST_CODE):
                    if (resultCode == Activity.RESULT_OK) {
                        Uri contactData = data.getData();
                        Cursor c = getContentResolver().query(contactData, null, null, null, null);
                        if (c.moveToFirst()) {
                            String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                            String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                            String num = "";
                            if (Integer.valueOf(hasNumber) == 1) {
                                Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                                while (numbers.moveToNext()) {
                                    num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    Toast.makeText(MainActivity.this, "Number=" + num, Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                        break;
                    }
            }
        }

    }
}

}


text:
Q: laravel website after registration gets stuck into controller sometimes i have a laravel website, which has login and registration, after registration, the values are entered in database and sent to email,
the register controller is as below:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Register;
use App\Mail\SendEmail;
use Session;
use Mail;
use Storage;
use Auth;
use App\User;
use Illuminate\Support\Facades\File;

class RegController extends Controller
{

    public function index()
    {
        //
    }

    public function userfind(Request $request)
    {
        $user =   User::where('username',$request->user)->value('username');
        return  $user;
    }

    public function userfindemail(Request $request)
    {
        $user =   User::where('email',$request->email)->value('email');
        return  $user;
    }

    public function create()
    {
        //
    }

    public function store(Request $request)
    {

        // return $request->Fee;
        $data = new Register;
        $data->firstname = $request->firstname;
        $data->lastname = $request->lastname;
        $data->mobilenumber = $request->mobilenumber;
        $data->experience = $request->experience;
        $data->designation = $request->designation;
        $data->confirmation = $request->confirmation;
        $data->company = $request->company;
        $data->address = $request->address;
        $data->addressline2 = $request->addressline2;
        $data->city = $request->city;
        $data->state = $request->state;
        $data->pin = $request->pin;
        $data->country = $request->country;
        $data->Whatsapp = $request->Whatsapp;
        $data->alternatenumber = $request->alternatenumber;
        $data->Email = $request->Email;
        $data->CompanyRegNumber = $request->CompanyRegNumber;
        $data->Date_Incorporation_orBusi_Stp = $request->Date_Incorporation_orBusi_Stp;
        $data->GSTIN = $request->GSTIN;
        $data->Services_Offered = $request->Services_Offered;
        $data->Annual_Turnover = $request->Annual_Turnover;
        $data->Declaration = $request->Declaration;
        $data->Fee = $request->Fee;

        $data->termsandconditions = $request->termsandconditions;
        // $data->Fee = $request->Fee;
        $data->Mode_of_Payment = $request->Mode_of_Payment;

        $data->Recommended_by_A = $request->Recommended_by_A;

        $data->Recommended_by_B = $request->Recommended_by_B;

        // user login
        $user = new User;
        $user->name = $request->firstname." ".$request->lastname;
        $user->email = $request->Email;
        $user->username = $request->username;
        $user->password =  bcrypt($request->password);
        $user->save();

        $data->user_id =  $user->id;

        if($request->hasFile('Photo')) {
            $image = $request->file('Photo');
            $filename = time().$image->getClientOriginalName();
            $destinationPath = public_path('uploads/Photo');

            Storage::disk('public')->put($filename,  File::get($image));
            $data->Photo=$filename;
        }
        if($request->hasFile('Receipt')) {
            $image = $request->file('Receipt');
            $filename = time().$image->getClientOriginalName();
            $destinationPath = public_path('uploads/Receipt');
            Storage::disk('public')->put($filename,  File::get($image));
            $data->Receipt=$filename;
        }
        if($request->hasFile('Signature')) {
            $image = $request->file('Signature');
            $filename = time().$image->getClientOriginalName();
            $destinationPath = public_path('uploads/Signature');
            Storage::disk('public')->put($filename,  File::get($image));
            $data->Signature=$filename;
        }

        $data->save();
        Session::flash('registered','reg');

        $name = $request->firstname." ".$request->lastname;
        $subject = "TEIA";
        $message =  $data->id;

        $photo = $data->Photo;
        $sign = $data->Signature;
        $recipt= $data->Receipt;
        $email = 'teiamembers@gmail.com';
        $smail= $request->Email;

        // ->cc(['name1@domain.com','name2@domain.com'])
        Mail::to($email)->cc([$smail])->send( new SendEmail($subject,$message , $photo ,$sign,$recipt));

        //
        // return redirect('demo')->with(['reg'=>$data]);

        return back();
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        $data =  Register::find($id);
        $data->firstname = $request->firstname;
        $data->lastname = $request->lastname;
        $data->mobilenumber = $request->mobilenumber;
        $data->experience = $request->experience;
        $data->designation = $request->designation;
        $data->confirmation = $request->confirmation;
        $data->company = $request->company;
        $data->address = $request->address;
        $data->addressline2 = $request->addressline2;
        $data->city = $request->city;
        $data->state = $request->state;
        $data->pin = $request->pin;
        $data->country = $request->country;
        $data->Whatsapp = $request->Whatsapp;
        $data->alternatenumber = $request->alternatenumber;
        $data->Email = $request->Email;
        $data->CompanyRegNumber = $request->CompanyRegNumber;
        $data->Date_Incorporation_orBusi_Stp = $request->Date_Incorporation_orBusi_Stp;
        $data->GSTIN = $request->GSTIN;
        $data->Services_Offered = $request->Services_Offered;
        $data->Annual_Turnover = $request->Annual_Turnover;
        $data->Declaration = $request->Declaration;
        $data->Fee = $request->Fee;

        $data->termsandconditions = $request->termsandconditions;
        // $data->Fee = $request->Fee;
        $data->Mode_of_Payment = $request->Mode_of_Payment;

        $data->Recommended_by_A = $request->Recommended_by_A;

        $data->Recommended_by_B = $request->Recommended_by_B;

        // user login
        $user =  User::find(Auth::user()->id);
        $user->name = $request->firstname." ".$request->lastname;
        $user->email = $request->Email;
        $user->username = $request->username;

        $user->save();

        $data->user_id =  $user->id;

        if($request->hasFile('Photo')) {
            $image = $request->file('Photo');
            $filename = time().$image->getClientOriginalName();
            $destinationPath = public_path('uploads/Photo');

            Storage::disk('public')->put($filename,  File::get($image));
            $data->Photo=$filename;
        }
        if($request->hasFile('Receipt')) {
            $image = $request->file('Receipt');
            $filename = time().$image->getClientOriginalName();
            $destinationPath = public_path('uploads/Receipt');
            Storage::disk('public')->put($filename,  File::get($image));
            $data->Receipt=$filename;
        }
        if($request->hasFile('Signature')) {
            $image = $request->file('Signature');
            $filename = time().$image->getClientOriginalName();
            $destinationPath = public_path('uploads/Signature');
            Storage::disk('public')->put($filename,  File::get($image));
            $data->Signature=$filename;
        }

        $data->save();

        return back();
    }

    public function destroy($id)
    {
        //
    }
}

so the problem is, after successful registration, the same page should load showing success message, its happening sometimes, so sometimes after successful registration, the page is stuck in register controller and displays blank white page which is the controller itself, can anyone please help me with this. thanks in advance.
here is my website link https://teia.website/teia

A: buddy,Use Exception handling for debugging purpose, like try and catch.
maybe that will help whats wrong with the code.
If that dosent help, then look into your controller method is there any printing variable, like dd($request->all()).


text:
Q: Rotating a div using JavaScript I am sorry that title is not really specific what I want to achieve using JavaScript.
I want to create a effect in which a div (Black Rectangle) is rotating on X axis and going
downwards. Its like by flipping its moving downwards.
And please no jQuery!
Any kind of hint would be appreciated.
Image of effect I want to achieve:

//don't know what to do in flip function
function flip(a,b) {
    var d=document.getElementById('box');
    d.style.transform="rotateX("+a+"deg)";
    d.style.transformOrigin=b;
    //alert(b);
}

setTimeout(function() {
    flip(180, "bottom");
}, 1000);

setTimeout(function() {
    flip(180, "top");
}, 2000);
.box {
    left:0px;
    top:0px;
    height:100px;
    width:100px;
    transition-property:all;
    transition-duration:1s;

    position:absolute;
    background-color:#555;
}
<div class="box" id="box"> </div>


text:
Q: Editing the current page on view pager I am working on an viewpager with previous and next page. What I need is to increase the text of the current page, after loading the page. But while I am trying, text on the next page is changing (I know that next and previous page load on viewpager). How can I get the focused on one selected page?
What I have done is,
viewPager.setClipChildren(false);

unfortunately it doesn't work..

A: i didn't really understand what you need but i think you may use this:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
           //Edit
            if(position==int requiredPosition)
            {
                 // resize your text
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

A: I recommed using position parameter in activity and you can update text based on the position recieved.
This example is for Fragments though
@Override
    public Fragment getItem(int position) {
        return PageFragment.newInstance(position);
    }

And in fragment you recieve this position as an argument:
public static PageFragment newInstance(int position) {
    Bundle args = new Bundle();
    args.putInt("position", position);
    PageFragment page = new PageFragment();
    page.setArguments(args);
    return page;
}

In onCreateView you update your textview based on your position.
If you want to update TextView something like this:
TextView tv = (TextView) view.findViewById(R.id.yourId);
int position = getArguments().getInt("position");
tv.setText("This is page number: " + position);


text:
Q: Error message "Thread1:signal SIGABRT" on "return 0" I wrote a code in C-programming trying to search words in a string and replace this words with other words.
Everything seems good when it is running, but there is a error happened at the line "return 0" with a message "Thread 1:signal SIGABRT".
I have no clue to track where the problem is. Does anyone have any idea about it?
The following is my code:
int main(void){
    char s1[]="ABCDABCD";
    char *s2="BC";
    char *s3="xyz";
    int ReplaceStr(char *, char *, char *);
    char *pps1=s1;
    printf("%s\n", s1);
    ReplaceStr(pps1, s2, s3);
    printf("%s\n", s1);
    return 0;
}

int ReplaceStr(char *pps1, char *ps2, char *ps3){
    if(pps1==NULL || ps2==NULL || ps3==NULL) return 0;
    int n1=strlen(pps1), n2=strlen(ps2), n3=strlen(ps3);
    if(!n1 || !n2) return 0;
    char *sNext=strstr(pps1, ps2);
    char *sNext1=sNext+n2;
    if(sNext==NULL) return 0;
    int count=0;
    char *Tmp=calloc(sizeof(char), strlen(sNext1)+1);;
    if(sNext != NULL){
        strcpy(Tmp, sNext1);
        memcpy(sNext, ps3, n3);
        strcpy(sNext+n3, Tmp);
        sNext+=strlen(ps3);
        count+=ReplaceStr(sNext, ps2, ps3)+1;
    }
    free(Tmp);
    return count;
}

*

*s1: a string for being searched

*s2: the words I want to look for

*s3: the words which will replace s2

A: I am not sure at the moment why you claim the error is at the line return 0 at the end of main.  What IDE/compiler are you using?
Try rewriting your code like this:
int ReplaceStr(char*, char*, char*);    // {1}

int main() {
    char *s1="ABCDABCD";   // {2}
    char *s2="BC";
    char *s3="xyz";
    char *pps1=s1;
    printf("%s\n", s1);
    ReplaceStr(pps1, s2, s3);
    printf("%s\n", s1);
    return 0;
}

int ReplaceStr(char *pps1, char *ps2, char *ps3){
    if(pps1==NULL || ps2==NULL || ps3==NULL) return 0;
    int n1=strlen(pps1), n2=strlen(ps2), n3=strlen(ps3);
    if(!n1 || !n2) return 0;
    char *sNext=strstr(pps1, ps2);
    char *sNext1=sNext+n2;
    if(sNext==NULL) return 0;
    int count=0;
    char *Tmp= (char*) calloc(sizeof(char), strlen(sNext1)+1);  // {3}
    if(sNext != NULL){
        strcpy(Tmp, sNext1);
        memcpy(sNext, ps3, n3);
        strcpy(sNext+n3, Tmp);
        sNext+=strlen(ps3);
        count+=ReplaceStr(sNext, ps2, ps3)+1;
    }
    free(Tmp);
    return count; }

At edit {1}, I declared the function you are to use before main.
At edit {2}, I changed s1[]="" for consistency.  It irked me.
And at edit {3}, calloc returns a void*, and so you have to cast it to the type of pointer you want.


text:
Q: How to get the specific property value from SOPAUI response? Whenever I am executing the testcases, I will get the property value  in response as myscore Arun/ten2016-12-20
Here the key is myscore and value isArun/ten2016-12-20. The date will be changing dynamically as today date append with the text 'Arun/ten'
I tried by adding the below groovy script code but its not working,
today = new Date().format("yyyy-MM-dd")
log.info today

def s=log.info("Arun/ten" + today);

assert messageExchange.responseHeaders["my_client_update"] == ["s"]

I want this script to be passed.
The same i have passed in the script assertion like below,
assert messageExchange.responseHeaders["my_client_update"] == ["s"]
Kindly suggest the solution.

A: Your Script Assertion is almost near except that one statement has trivial issue.
Here is what you would need the script to be, and note that below script is using simple regular expression for date as that is dynamic. Of course, you may also use in the same way as convenient to you.
/**
* Below is the Script Assertion
* Retrieves the specified header and asserts against the expected value
**/

//Change the header key as needed.
def requiredHeaderKey = 'my_client_update'

//Change the expected value for the above Header key
//Note that below one is using the regular expression to accommodate dynamic date in the header value
def expectedRequiredHeaderValue = "Arun/ten\\d{4}-\\d{2}-\\d{2}"

//You may not be required to change beyond this point of the script.

//Check if the response has headers
assert messageExchange.responseHeaders, "There are no headers in the response"

//Get & Check if the response has required Header and its value is not empty
def requiredHeaderValue = messageExchange.responseHeaders[requiredHeaderKey]
assert requiredHeaderValue, "Value of the response header ${requiredHeaderKey} is empty or null"

if (requiredHeaderValue instanceof List) {
  log.info "Requested header value is ${requiredHeaderValue[0]}"
  assert requiredHeaderValue[0] ==~ expectedRequiredHeaderValue, "Response header value is not matching with the expected value"
}


text:
Q: In a procedure connect to 2 databases: one local and the other remote I'm trying to write a stored procedure, in DB2 for AS400, which runs a query on the local database (the same where the procedure is stored; it's named DBLocale) and an other on a remote database (let's call it DBRemoto). In iSeries Navigator I can see both of them selecting "Database" node.
I tried something with CONNECT TO DBRemoto; and/or SET CONNECTION DBRemoto;, but got weird results: "connection already exists", "connection doesn't exist", "CALL instruction completed" (but no result set) etc. .
This would be what I expect to do:
CREATE PROCEDURE MYLIB.TEST_CONNECT_INSIDE_PROCEDURE
DYNAMIC RESULT SETS 1
LANGUAGE SQL
READS SQL DATA
BEGIN
    DECLARE sql_string VARCHAR(1024) DEFAULT '';
    DECLARE locale INT DEFAULT -1;
    DECLARE remoto INT DEFAULT -1;
    DECLARE cur CURSOR FOR stmt;
    DECLARE curOut CURSOR FOR select locale, remoto from SYSIBM.SYSDUMMY1;

    -- run the same query in both DBs; I checked, results must be different
    SET sql_string = 'select count(*) as QTY from MYLIB.MYTABLE';

    -- run locally
    CONNECT TO DBLocale; --it's one of my attempts
    PREPARE stmt FROM sql_string;
    OPEN cur;
    FETCH cur INTO locale;
    CLOSE cur;

    -- run remotely
    CONNECT TO DBRemoto; --it's one of my attempts
    PREPARE stmt FROM sql_string;
    OPEN cur;
    FETCH cur INTO remoto;
    CLOSE cur;

    -- output results
    OPEN curOut;
    SET RESULT SETS CURSOR curOut;
END;

I call it with
call MYLIB.TEST_CONNECT_INSIDE_PROCEDURE()

Can someone tell me if it is possible and clarify how it works, please? If it's not possible in a procedure, is there a workaround? Many thanks!

A: On IBM i, you need to include both the user and password parameters for remote databases.
CONNECT TO DBRemoto USER QUAGMEIER USING 'GIGIDY'

The password needs to be in upper case and at least in embedded RPG it needs to be in a host variable.

A: Under IBM i 7.1, Technical Refresh 4 allows connection to multiple databases and 3-part naming.  This means a table (or view) reference can take the form dbname.schema.table, as long as dbname is an entry in the Relational Database Directory.


text:
Q: local variable performance in Javascript vs C# My Javascript code here. Instead of everytime trying to access document which is global context we made it to activation object. So that we can improve our read/write performance.
function initUI(){
        var doc = document,
            bd = doc.body,
            links = doc.getElementsByTagName("a"),
            i= 0,
            len = links.length;
        while(i < len){
            update(links[i++]);
        }
        doc.getElementById("go-btn").onclick = function(){
            start();
        };
        bd.className = "active";
    }

Whether is it applicable to C# as well?
Lets say,
defining var customObject = new CustomClass(); as a member variable and accessing like below,
void MyMethod()
{
var obj = customObject;
var name = obj.name;
//some code here
..
..
}

will increase the performance?

A: No, it's not the same in C#.
In javascript, you cache the DOM objects, because the DOM is awfully slow to read/write.
You don't need to cache normal objects properties. If you do it, it is to gain some characters, but not for performance.
In C#, you don't have to deal with the DOM. You don't need to cache the objects, except if you want to gain some characters.


text:
Q: Need help styling on javascript var stateData = {
     MA: { fullName: 'Massachusetts: some  infor here | some info here | test'},
     VA: { fullName: 'Virginia:' },
     VA: { fullName: 'Virginia' },
     VA: { fullName: 'Virginia' },
     VA: { fullName: 'Virginia' },
     VA: { fullName: 'Virginia' },
     VA: { fullName: 'Virginia' },
     VA: { fullName: 'Virginia' },
     VA: { fullName: 'Virginia' }
    // other states' data...
}

I need help styling the code inside MA, it does not let me put line breaks or anything. Thanks for the help!

A: Sorry, this post is a bit too length for the comment box.
\n is the universal newline character.
But perhaps you should look at this alternative:
var stateData = {
    MA: {
        fullName: 'Massachusetts',
        motto: 'A catchy expression here',
        information: 'More data here',
        population: 1000
    },
}

To me it looks like you are building some JSON that you'll probably reference like:
stateData.MA.fullName

It's considered bad practice to format your raw data. You should probably do this when you use the data:
console.log('Now you\'ve travelled to: ' + stateData.MA.fullName + "/n" + stateData.MA.motto);

Just a thought.

A: If you want a line break within a JavaScript string then you should do \n (which stands for new line)


text:
Q: Treat delimiters as input tokens I'd like to know how to do this in both C++ and Java (EDIT: I don't mean simultaneously.  I'm asking two similar questions, "How do I do this in C++?" and "How do I do this in Java?").
I want to parse input from a file and treat '(' and ')' as delimiters in addition to whitespace.  But I also want each encounter of '(' or ')' to be recognized as an individual token. So for example when parsing

This contians (nested (parentheses))

I would like successive calls to next() (or >>) to give (one per line)
This
contains
(
nested
(
parentheses
)
)
<end of input>

Are there parsers/scanners with this functionality built-in?  I know Java's Scanner is powerful, but as far as I can tell there's no way to determine which delimiter was matched each time you encounter the next token.

A: Compiler-compiler discussion aside, this kind of parser can be naively implemented using two indices, something like this:
for(int i = 0; i < str.size(); ) {
  int j = i;
  for(; j < str.size(); ++j) {
    // check for spaces
    if(str[j] == ' ') {
      // capture substring index i to j-1 as a token
      i = j+1;
      break;
    }

    // check for brackets
    if(str[j] == '(' || str[j] == ')') {
      // str[j] is a token
      i = j+1;
      break;
    }

  }

  // no more characters to check
  if(j >= str.size()) break;
}

Basically i is a marker to indicate start of a token, and j is used to search where the token ends.
Disclaimer: code above is not tested, might contain syntax error and bug especially with empty input, blanks etc, and likely to perform poorly over large data. Please consider using 3rd party library before reinventing the wheel.
Or for solution with minimal amount of code, you can just replace every occurrence of "(" with " ( " (likewise with ")") and do a white space tokenisation:
str.replaceAll("(", " ( ").split("\s+");

A: This should be easily handled by a regular expression.
Something along the lines of `"\\s*(?:(\\w+)|([()]))" should do
the trick in C++11 (for earlier versions of C++, you'd need
Boost regular expressions).  Java also has regular expression
support, so you should be able to do the same there.
In both cases, the above expression skips white space, then
"captures" a symbol in group 1, or the parentheses in group 2.


text:
Q: SSH Server on Ubuntu no longer working I restarted my server today and my SSH server stopped working. Docker is still running, the database is up, but connections to the SSH server are timing out.
I made sure that it's not the firewall, tested it from another device from a different location, reinstalled the SSH server, but nothing seems to work (did it in rescue mode). I didn't found anything important in the logs. Port seems to be closed from the outside, but logs indicate the server is running.
Docker is using the ports 80, 443, 53. I run a Cassandra database on the default ports. All of those are listening and I'm able to connect to them perfectly fine (except SSH as mentioned). SSH server is running on a custom port. I tried disabling UFW and changing the SSH port. I didn't change the SSH settings in a while and they worked after previous restarts.
Some output of: cat /var/log/auth.log
Oct  3 22:03:49 gd-1 sshd[1096]: Server listening on 0.0.0.0 port 30XXX.
Oct  3 22:03:49 gd-1 sshd[1096]: Server listening on :: port 30XXX.
Oct  3 22:17:01 gd-1 CRON[19718]: pam_unix(cron:session): session opened for user root by (uid=0)
Oct  3 22:17:01 gd-1 CRON[19718]: pam_unix(cron:session): session closed for user root
Oct  3 22:35:11 gd-1 systemd-logind[644]: Power key pressed.
Oct  3 22:35:11 gd-1 systemd-logind[644]: Powering Off...
Oct  3 22:35:11 gd-1 systemd-logind[644]: System is powering down.

I'll add more info as requested, but I'm out of ideas. Any clues?


text:
Q: Automapper ignores DTO inside of DTO I am having a Azure Mobile Service and its running fine except i have problems with AutoMapper and DTO's with other DTO's inside of them. Basically they are ignored in the output.
My Data class:
public class FoodSupplyProvider
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Index(IsClustered = true)]
    [Key]
    public int FoodSupplyProviderId { get; set; }
    public string Name { get; set; }
    public virtual Branche Branche { get; set; }
}

public class Branche
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Index(IsClustered = true)]
    [Key]
    public int BrancheId { get; set; }
    public string BrancheName { get; set; }
}

My DTO classes
public class BrancheDTO : EntityData
{
    public string BrancheName { get; set; }
}

public class FoodSupplyProviderDTO : EntityData
{
    public string Name { get; set; }
    public BrancheDTO Branche { get; set; }
}

I have registered the mappings with the Mapper:
cfg.CreateMap<Branche, BrancheDTO>();
cfg.CreateMap<FoodSupplyProvider, FoodSupplyProviderDTO>();

Output:
When i try to output the FoodSupplyProviderDTO, it is as follows:
[{
"id":"2b3fdde5-ba55-4e7f-ae74-5e23abaa7b64",
"name":"FoodSupplyProvider Name 1"
}]

I would expect it to be:
[{
"id":"2b3fdde5-ba55-4e7f-ae74-5e23abaa7b64",
"name":"FoodSupplyProvider Name 1"
"branche":"The BrancheDTO goes here...."
}]

Please note, the expected output is also what the documentation says on my API.
I have checked that the value is not null, i have even tried mapping the Name of the Branche to the Name of the FoodSupplyProviderDTO and that works perfectly fine, except that the Branche is still not present in the output.
EDIT:
As @YacoubMassad said, it could be the mapping or the serilization fail. I have tried outputting the mapping and it works as intended. I then tried to json serialize it in code and output the result. That one is as the expected result shown above.
So the problem lies with the WebApi serialising the object for me. Is there anyway i can debug this?


text:
Q: AspectJ non-Spring annotations not intercepting adviced methods I wanted to use AOP-styled annotations for @Around advice in a non-Spring project. I was able to make up some code, but it's been giving me trouble - instead of seeing the console output as coded in the Advice I can only see the SampleClass method's printout.
Providing a minimal, reproductible example of my code. Hoping to get some hint on how to get it working. Thanks!
Main.java
package pl.bart;

public class Main {
    public static void main(String[] args) {
        System.out.println(new SampleClass().a());
    }
}

SampleClass.java
package pl.bart;

public class SampleClass {

    @Annotation
    public String a() {
        return "Hello from sample class";
    }

}

Annotation.java
package pl.bart;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Annotation {
}

Advice.java
package pl.bart;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class Advice {
    @Pointcut("@annotation(Annotation)")
    public void callAt() {

    }

    @Around("callAt()")
    public Object advice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Hello from advice");
        return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }
}

META-INF/aop.xml
<aspectj>
    <aspects>
        <aspect name="pl.bart.Advice"/>
        <weaver options="-verbose -showWeaveInfo">
            <include within="pl.bart.*"/>
        </weaver>
    </aspects>
</aspectj>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pl.bart</groupId>
    <artifactId>aspectj-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>

        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <argLine>
                        -javaagent:"${settings.localRepository}"/org/aspectj/
                        aspectjweaver/1.8.9/
                        aspectjweaver-1.8.9.jar
                    </argLine>
                    <useSystemClassLoader>true</useSystemClassLoader>
                    <forkMode>always</forkMode>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.14.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

A: The are three mistakes in you project.
1.
    @Pointcut("@annotation(Annotation)")
    public void callAt() {

    }

use fully qualified names of classes, i.e. pl.bart.Annotation instead of Annotation - it costs you nothing but saves a lot of time, in particular aspectj 1.5.4 "does not support" simple names.
2.
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>

        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.4</version>
        </dependency>

aspectj does some magic with bytecode, and it is too naive to expect the library released 12 years ago supports java 17, switch to the recent aspectj 1.9.9, also note you need to add --add-opens java.base/java.lang=ALL-UNNAMED to JVM arguments.
3.
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.14.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

if you are going to use load time weaving and you don't use native aspectJ (.aj) syntax, you do not need aspectj-maven-plugin - it compiles .aj files and performs compile time weaving.


text:
Q: How do I get the opposite of the if construct in Bash? if date -d "2012010123" runs if the date command returns a zero exit code. How do I get the opposite to occur? In other words, how can I get the if statement to run if the exit code is 1?

A: Negate it:
if ! date -d "2012010123"; then
  # do something here (date returned with non-zero exit code)
fi

if takes a command pipeline (or a list thereof), and of pipelines man bash says this:

The  return  status of a pipeline is the exit status of the last command[...]  If the reserved word !  precedes  a  pipeline,  the
exit status of that pipeline is the logical negation of the exit status as described above.


text:
Q: python csv reader not reading all rows So I've got about 5008 rows in a CSV file, a total of 5009 with the headers. I'm creating and writing this file all within the same script. But when i read it at the end, with either pandas pd.read_csv, or python3's csv module, and print the len, it outputs 4967. I checked the file for any weird characters that may be confusing python but don't see any. All the data is delimited by commas.
I also opened it in sublime and it shows 5009 rows not 4967.
I could try other methods from pandas like merge or concat, but if python wont read the csv correct, that's no use.
This is one method i tried.
df1=pd.read_csv('out.csv',quoting=csv.QUOTE_NONE, error_bad_lines=False)
df2=pd.read_excel(xlsfile)

print (len(df1))#4967
print (len(df2))#5008

df2['Location']=df1['Location']
df2['Sublocation']=df1['Sublocation']
df2['Zone']=df1['Zone']
df2['Subnet Type']=df1['Subnet Type']
df2['Description']=df1['Description']

newfile = input("Enter a name for the combined csv file: ")
print('Saving to new csv file...')
df2.to_csv(newfile, index=False)
print('Done.')

target.close()

Another way I tried is
dfcsv = pd.read_csv('out.csv')

wb = xlrd.open_workbook(xlsfile)
ws = wb.sheet_by_index(0)
xlsdata = []
for rx in range(ws.nrows):
    xlsdata.append(ws.row_values(rx))

print (len(dfcsv))#4967
print (len(xlsdata))#5009

df1 = pd.DataFrame(data=dfcsv)
df2 = pd.DataFrame(data=xlsdata)

df3 = pd.concat([df2,df1], axis=1)

newfile = input("Enter a name for the combined csv file: ")
print('Saving to new csv file...')
df3.to_csv(newfile, index=False)
print('Done.')

target.close()

But not matter what way I try the CSV file is the actual issue, python is writing it correctly but not reading it correctly.
Edit: Weirdest part is that i'm getting absolutely no encoding errors or any errors when running the code...
Edit2: Tried testing it with nrows param in first code example, works up to 4000 rows. Soon as i specify 5000 rows, it reads only 4967.
Edit3: manually saved csv file with my data instead of using the one written by the program, and it read 5008 rows. Why is python not writing the csv file correctly?

A: I ran into this issue also. I realized that some of my lines had open-ended quotes, which was for some reason interfering with the reader.
So for example, some rows were written as:
GO:0000026  molecular_function  "alpha-1
GO:0000027  biological_process  ribosomal large subunit assembly
GO:0000033  molecular_function  "alpha-1

and this led to rows being read incorrectly. (Unfortunately I don't know enough about how csvreader works to tell you why. Hopefully someone can clarify the quote behavior!)
I just removed the quotes and it worked out.
Edited: This option works too, if you want to maintain the quotes:
quotechar=None

A: My best guess without seeing the file is that you have some lines with too many or not enough commas, maybe due to values like foo,bar.
Please try setting error_bad_lines=True. From Pandas documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html to see if it catches lines with errors in them, and my guess is that there will be 41 such lines.

error_bad_lines : boolean, default True
  Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these "bad lines" will dropped from the DataFrame that is returned. (Only valid with C parser)

The csv.QUOTE_NONE option seems to not quote fields and replace the current delimiter with escape_char + delimiter when writing, but you didn't paste your writing code, but on read it's unclear what this option does. https://docs.python.org/3/library/csv.html#csv.Dialect


text:
Q: wtforms & flask: populate RadioField i have a form with several RadioFields:
from wtforms import Form, RadioField

class AnswerForm(Form):  # type: ignore

    answer = RadioField(
        "Answer",
        choices=(
            ("A", "yes"),
            ("B", "don't care"),
            ("C", "no"),
        ),
    )

if i run that in a POST request,i can populate the form with the data from request.post:
AnswerForm(
        formdata=request.form,
        prefix="3",
 )

request.form contains:
{"3-answer": "B"}

and that works fine.
but i may want to fill the values from a dictionary (e.g. from the database - especially in a GET request) and maybe merge that with request.from (which is immutable). i tried this:
form_data = dict(request.form)
# update form_data with values from db

AnswerForm(
        # formdata=request.form,
        data=from_data,
        prefix="3",
    )

but that does not work: the form is empty - no item is selected anymore.
what am i doing wrong? how can i fill the AnswerForm with values from the database (and maybe even merge them with values from request.form)?

A: the best i came up with so far is this:
request_form = request.form.copy()
request_form.add("3-answer", "B")
AnswerForm(
    formdata=request_form,
    prefix="3",
)

but i guess there re better ways to do that...


text:
Q: resend your request with the updated header Transmission in Swift I've this code to take the X-Transmission-Session-Id but now i need to resend the request with the updated header.
function takeXTransmissionSessionId( ){

    let urls = NSURL(string: "\(url)")
    let task = NSURLSession.sharedSession().dataTaskWithURL(urls!) { (data, respornse, error) -> Void in

        guard error == nil && data != nil else {

            print("error=\(error!)")

            let alertView = UIAlertController(title: "ERROR", message: "A server with the specified hostname could not be found.", preferredStyle: UIAlertControllerStyle.Alert)
            let actionView = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
            alertView.addAction(actionView)
            self.presentViewController(alertView, animated: true, completion: nil)

            return
        }

        if let httpStatus = respornse as? NSHTTPURLResponse where httpStatus.statusCode != 200 {

            let sesionID = httpStatus.allHeaderFields["X-Transmission-Session-Id"]

            if sesionID == nil {

                let alertView = UIAlertController(title: "ERROR", message: "The request has not been applied because it lacks valid authentication credentials for the target resource.", preferredStyle: UIAlertControllerStyle.Alert)
                let actionView = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
                alertView.addAction(actionView)
                self.presentViewController(alertView, animated: true, completion: nil)

            }else{

                //print("\(respornse!)")
                //print("\(sesionID!)")
                self.XTransmissionSessionId = "\(sesionID!)"

            }

        }

    }

    task.resume()

}

My problem is i tray many times in a different ways but i don't know what i need to do.
Thanks!

A: This is the code for do what i need:
request.HTTPMethod = "POST"
    request.addValue("\(XTransmissionSessionId)", forHTTPHeaderField: "X-Transmission-Session-Id")


text:
Q: Conditionally update date in a dataframe I have the following data.
 df_a <- data.frame(id=c("John","Ben","Bill", "Eminem"),
                     amount=c("300", "500", "1000", "1200"),
                     issue_date=as.Date(c("2010-01-01","2011-01-01","2012-01-01", "2015-02-01")),
                     last_pymnt_date=as.Date(c("2013-02-01","2012-05-01","2014-01-01", "2018-02-01")),
                     months_passed=c(37,16,24,36),
                     term = c("36", "36", "36", "36"),
                     status=c("Fully Paid",
                              "Charged off",
                              "Does not meet the credit policy. Status:Charged Off",
                              "Does not meet the credit policy. Status:Fully Paid"),
                     stringsAsFactors = F)

    library(DescTools)
    df_a$maturity_dt <- AddMonths(df_a$issue_date, 36)

I want to make the last_pymnt_date same as maturity_dt if status variable includes the expression "Fully Paid". If I run the following line it makes last_pymnt_date variable some numbers.
df_a$last_pymnt_date <- ifelse(grepl("Fully Paid", df_a$status),
                               df_a$maturity_dt,
                               df_a$last_pymnt_date)

Any suggestion?
Thanks

A: Here's a simple way to do this. Just separated out grepl test to improve readability.
test <- grepl("Fully Paid", df_a$status)

df_a$last_pymnt_date[test] <- df_a$maturity_dt[test]

A: Solution using dplyr:
df_a$last_pymnt_date <- dplyr::if_else(grepl("Fully Paid", df_a$status),
                                       df_a$maturity_dt,
                                       df_a$last_pymnt_date)

dplyr's case_when is also a good alternative to ifelse, especially if you have more conditions:
df_a$last_pymnt_date <- dplyr::case_when(
                                   grepl("Fully Paid", df_a$status) ~ df_a$maturity_dt,
                                   TRUE ~ df_a$last_pymnt_date)

Or using data.table:
library(data.table)

df_a <- setDT(df_a)[grepl("Fully Paid", status), last_pymnt_date := maturity_dt]


text:
Q: simple_html_dom find links on page and scrape details from each I have one page with several links, each link lead to new page with details in table. I want to store all links from original page and scrape table data from each link (page).
So:
OriginalPage -|- Link1 -> TableData
              |- Link2 -> TableData
              |- Link3 -> TableData

I success extract links from original page, and table data from one link, but I don't know how to make loop to extract data from all links at once.
All link have a simple pattern, and all pages have same table (but different data).
This is what I have:
    $city1 = file_get_html('http://www.xxxx.xx/sl/cities/city1');
    // Get links from page that contain word "info" and extract date from URL (date is important)
//Example link on original page: http://www.xxxx.xx/sl/cities/info-onday-19-05-2017-d"
    foreach($city1->find('a[href]') as $link){
        if(strstr($link, 'info')){
            preg_match('#onday (.*?). #', $link, $match);
            $date = $match[1];
        }
    }
    //Get table data from one link
    $city1DetailsUrl = "http://www.xxxx.xx/sl/cities/info-onday-".$date."-d";

    $city1Details = file_get_html($city1DetailsUrl);
    $table = $city1Details->find('table', 0);
    $rowData = array();
    foreach($table->find('tr') as $row) {
        // initialize array to store the cell data from each row
        $info = array();
        foreach($row->find('td') as $cell) {
            // push the cell's text to the array
            $info[] = $cell->plaintext;
        }
        $rowData[] = $info;
    }
    foreach ($rowData as $row => $tr) {
        foreach ($tr as $td) {
            echo  $td .'<br>';
        }
    }

Summary: find links on original page that contain some word (info), scrapte table data from each that link (page).


text:
Q: Template not coming up when I run my Ember Server I have created a very simple application template on a newly created Ember app that just has a title of "Casteva" and h1 of "Welcome to Casteva.  It is in my application.emblem file within templates and looks like this:
#title Casteva

h1 Welcome to Casteva

== outlet

However, whenever I run Ember server, a blank page is the only thing that appears.  Any ideas on why this is?

A: ember install ember-cli-emblem


text:
Q: Write multiple SD cards in parallel, or serially as efficiently as possible A friend has handheld devices (Kindles) that we want to transfer a large bundle of files to (videos for a youth project). The devices have SD card readers and so we want to write SD cards with a disk image, or by another fast and efficient method.
Is it possible to, for example, get a USB adaptor with multiple ports, put each SD card in a USB converter, then simply write - eg with dd under Ubuntu - to say 8 SD cards at once.
We've also considered the possibility of having a computer, perhaps an RPi, such that when an SD card is inserted it gets written and umount-ed and ejected with no other manual intervention. Would this be easier/more efficient?
Is there a more efficient method we're missing? There is no wifi available, Bluetooth may be an option but I anticipate it being much slower. MS Windows or Linux (pref Ubuntu) options are useful to us. Thanks.

A: The device you are looking for is called "SD card duplicator". Prices range form $100 to above $1000. Your choice.


text:
Q: Node.js: Unhandled 'error' event I get an error from my Node.js application:
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: read ECONNRESET
    at errnoException (net.js:905:11)
    at TCP.onread (net.js:559:19)

I think I can catch this error by calling .on('error', function () {...}) on some object, but how can I find out on which object?

A: It's one of your TCP connections, but you are right that due to the short stack traces of an event loop, it can be a mystery to figure out. Even then, the intermediate libraries may not give convenient access to the actual connection instance that is the source of the error. If you just want to catch the error, process.onUncaughtException will give you a last resort mechanism to do so. You may also want to try Domains and see if they at least help you track down the source (as they will maintain a causal chain for you). There are also some long stack trace modules on npm that might help.
You may also have to start dividing your program into smaller parts to isolate the subsystem involved.


text:
Q: How to query for a co-occurence of events within elasticsearch? I'm trying to query for a co-ocurrence of events within a specified time range but can't seem to figure out how to actually perform such a query.
Consider, for example, that an excerpt of Events table looks something like this:

ID
@timestamp
event.action
agent.name

1
14:12:00
file-created
PC 1

2
14:15:00
permissions-changed
PC 2

3
14:28:34
created-process
PC 2

4
14:30:09
logged-in-explicit
PC 3

5
14:43:02
file-created
PC 3

6
14:52:43
privileged-service-called
PC 3

7
14:58:27
file-created
PC 2

8
15:01:28
logged-in
PC 1

9
15:02:00
permissions-changed
PC 1

The goal is to create an alert that would be generated when both file-created and created-process occurs by the same agent.name within 60 minutes of each other. The order of events does not matter. In other words, the above data should return two different alerts:

ID
@timestamp
agent.name
event.ids

1
14:58:27
PC 2
[2,7]

2
15:02:00
PC 1
[1,9]

In SQL this could be accomplished by joining the Events table on itself, but this doesn't seem to be possible with Elastic. Elastic does have the sequence query option, but this naturally requires a predefined sequence of events rather than an unordered group of events. While this could be done with two sequences without too much additional overhead, things get rather complicated when looking for the co-occurrence of three or more event.actions.
I looked into using the threshold rule, but there doesn't appear to be a way to check if multiple distinct threshold values can be checked for on an aggregate scale. I've also looked into the aggregate rule, but this only seems to support numerical aggregation.
One thought I had was to attempt to use a form of bit-stuffing as a means of being able to sum an entire binary column and then perform a mathematical bit-masking operation to determine if the desired event.action exists in the index, but this would make it super un-readable and difficult to debug.
Here's a short example of what I mean:
Beginning of Bit Stuffing Example

First, the mapping of the binary values:

event.action
agent.name
binary

file-created
PC 1
0000 0000 0001

permissions-changed
PC 1
0000 0000 0010

created-process
PC 1
0000 0000 0100

logged-in-explicit
PC 1
0000 0000 1000

privileged-service-called
PC 1
0000 0001 0000

logged-in
PC 1
0000 0010 0000

file-created
PC 2
0000 0100 0000

permissions-changed
PC 2
0000 1000 0000

created-process
PC 2
0001 0000 0000

logged-in-explicit
PC 2
0010 0000 0000

privileged-service-called
PC 2
0100 0000 0000

logged-in
PC 2
1000 0000 0000

Then, convert (some of) the rows from the Events table:

ID
@timestamp
event.action
agent.name
binary

1
14:12:00
file-created
PC 1
0000 0000 0001

2
14:15:00
permissions-changed
PC 2
0000 1000 0000

3
14:28:34
created-process
PC 2
0001 0000 0000

7
14:58:27
file-created
PC 2
0000 0100 0000

Then the bitwise addition (ORing) of the binary column:
   0000 0000 0001
   0000 1000 0000
   0001 0000 0000
   0000 0100 0000
 -----------------
   0001 1100 0001

Then with 0001 1100 0001 I can reference the mapping again to see that an alert should be generated since the 7th and 8th digit (from the right) are both true/1's.

End of Bit Stuffing Example
Apart from bit stuffing, another idea I had was to create a new index (something like file-process-created alert and then in the pipeline to that new index just query for two unique event.actions joined by agent.name. The issue with this idea is that it would ultimately generate an index per alert in addition to a rule searching for unique event.actions.
Any other ideas/solutions on how to go creating a double query inside of an outer query?


text:
Q: Apple Mail dosen't execute rule I want Apple Mail to mark all spam mails as read when they come in fomr IMAP. My provider marks them already with *****SPAM**** in the subject. Therefore I created this rule (Sorry for the german screenshot, I'm happy to post this in english if someone can tell me how).
Unfortunately the rule is never executed. Why?

A: As of OSX 10.8.3 it's possible to change the default rule for spam handling in mail.

*

*Open Mail

*Mail -> Preferences

*Choose the thrid option for the spam handling

*Click on the "Options" Button

*In the new window after the last action add a new one to mark the samp mails as read.

(It would be nice if some one with an english OSX could improve this :-) ).


text:
Q: How to create Revit Add-In DLL from Python I did a dumb thing. I got all excited about Revit 2014 allowing macros in Ruby, installed RevitRubyShell, and wrote what is going to become an add-in.
Slight problem -- there's no DLL compiler for IronRuby. D'oh!
So, I'm going to convert my code to Python (and use the excellent RevitPythonShell), which is what I was using for Revit API work before Revit 2014 Ruby came along.
My question is -- after I've converted my Ruby code to Python, (how) can I create a Revit Add-In DLL? I know that you can compile Python to a .NET DLL, but every example of Revit Add-Ins seems to be in C#. I want to stay in the interpreted environment because it's very fast to develop in Revit this way. But there's no point in doing all my dev in Python (or Ruby) if I have to convert everything to C# to make an Add-in that conforms to the IExternalApplication interface.
Has anyone done a Revit Add-In in Python?
Thanks!
Andy

A: Check out this blog post: Deploying RPS scripts with DeployRpsAddin.
In that article, I describe a functionality of the RevitPythonShell, that let's you create a distributable version of your RevitPythonShell (RPS) scripts - a bunch of scripts to ship.
The main way this is done is by providing a wrapper DLL written in C# that stores your scripts and a configuration file as resources and executes them with IronPython at runtime. This still means that your python code is not "compiled" to IL, but you get to bundle it up for installation on a separate computer. Check out the DesignPerformanceViewer for an elaborate example of such an AddIn.

A: Never mind. After more digging, found this stackoverflow answer that indicates IronPython DLLs are NOT portable/callable from anything but IronPython, so that leaves out Revit Add-ins.
Build .NET DLLs from Python code? (the answer, per this link, is "No.")


text:
Q: On my ASP.NET site: Input[type='file'] looks 'old' in IE11 On my ASP.NET site, <input type="file"> renders like this in IE11 (an oldschool look):

However, I want it to look like this (more modern look):

When trying <input type="file"> in the same IE11 elsewhere, in e.g. JSFiddle, it looks like I want it to (the more modern look).
I tried tracing CSS styles using F12 dev tools, but I cannot see any styles resulting in the oldschool look.
I'm using <!DOCTYPE html>.
My question: What might be causing the oldschool look?

A: IE11 Renders  that way.
If you want to change it you should use CSS, but it usually isn't easy.
What I usually do is to create my own fake component, with an input type text and a button styled the way I want.
I also have a input type file hidden, when I push my styled button I send via javascript a click to hidden input type file. When the file is selected I update my styled input type text with selected file name.


text:
Q: Импортирования в юнити Как правильно импортировать (к примеру пнг-шки интерфейса) по одному, т.е. каждая кнопка на отдельном файле, или все кнопки и панели в одном файле, может ли это как-то повлиять на занимаемую память? И как лучше делать что бы: качественее изображения - меньше занимаемой памяти?

A:
Как правильно импортировать (к примеру пнг-шки интерфейса) по одному, т.е. каждая кнопка на отдельном файле, или все кнопки и панели в одном файле

В самом идеальном варианте все должно быть в одном файле. Но на практике в юнити оставляют это все в отдельных ресурсах. Склеенными оставляют в основном какие-то 2д анимации.

Простота кода чаще важнее того мелкого порфита от быстродействия, который ты получаешь от склейки ресурсов. А склейка ресурсов означает усложнение кода (нужно, ведь, еще что бы юнити понимал из какого куска изображения вытягивать нужное)
Если уж что-то и влияет на быстродействие, то, чаще всего, совсем не это в первую очередь.

И как лучше делать что бы: качественее изображения - меньше занимаемой памяти?

Юнити не использует оригинальные изображения которые ты ему подсовываешь. Юнити сам конвертирует и пережимает файлы для себя. Ты лишь указываешь уровень сжатия(в настройках импорта ресурса).

A: Заходите в настройки текстуры которую вы загрузили. Далее выставляете ей признак Texture Type = Sprite (2D adn UI), Sprite Mode = Mulitle и заходите в SpriteEditor. В этом редакторе можно настроить разрезание атласа спрайта на отдельные изображения, задать их форму для физики и т.п. В проекте вы в последствии увидите все эти нарезанные изображения в качестве вложенных элементов вашей текстуры. Их можно использовать как текстуры для UI или как слайды анимации для 2D персонажа.


text:
Q: Fourier Series Coefficients I'm working on the following problem for my PDE's class as study for a test.

Sketch the Fourier series of
  $$ f(x) = 2x^2$$
  On the interval of $[-1,1]$.

My professors answer key states that the Fourier series for this function is $2x^2$ repeated over the interval $[-1,1]$ (I'd post the graph, but I'm not sure how.)
My understanding of the Fourier series is that for any function $f(x)$ is given by
$$ A_0 + \sum_{n=1}^\infty A_n \cos\bigg(\frac{n \pi x}{L} \bigg ) + \sum_{n=1}^\infty B_n \sin\bigg(\frac{n \pi x}{L} \bigg ) \tag{1}\label{1} $$
Where
 $$ A_0  = \frac{1}{2L} \int_{-L}^L f(x) dx$$
 $$ A_n =  \frac{1}{L} \int_{-L}^L f(x) \cos\bigg(\frac{n \pi x}{L} \bigg )dx$$
 $$ B_n =  \frac{1}{L} \int_{-L}^L f(x) \sin\bigg(\frac{n \pi x}{L} \bigg )dx$$
There are easier techniques to graphing the Fourier series of some function, but in attempting to solve this problem the hard way I find that
$$ A_0 = \frac{2}{3} $$
$$ A_n = \frac{8}{(n \pi)^2} (-1)^n $$
$$ B_n = 0 $$
When you plug these coefficients into $(\ref{1})$, you do not get $2x^2$ as my professor states.
I've worked this problem three times now and cannot seem to find my mistake. So my question, what are the correct coefficients for $f(x)$ along the interval $[-1,1]$?


text:
Q: Create new row after saving a record A user submits a url, this is put into into article.url through the scaffold create method.  I can parse the url like so:
def parse_url
  elements = @article.url.split("/")
  if(elements[0] == "http:")
    @home = elements[2] #elements[1] will be an empty string because of the // in the URL
  else
    @home = elements[0]
  end
end

What I would prefer to do is to parse the url after the user saves it with the create method and then insert this value into a new row in the database in the article table.

A: I'd use something like the following:
class Article
  attr_accessor :unparsed_url

  before_validation_on_save :parse_url

  private

  def parse_url
    return unless unparsed_url

    elements = unparsed_url.split("/")
    if(elements[0] == "http:")
      self.home = elements[2]
    else
      self.home = elements[0]
    end
  end
end

You'd use unparsed_url in the Rails forms.  Using a virtual attribute like this will work nicely with form validation.


text:
Q: nestjs, GRPC server and micro services architecture I've started a new project with nestjs with microservices, but it's my first microservices project and i don't' have enough knowledge.
During my documentation study, I can't find a way to use a microservice with grpc and HTTP at the same time.
In my architecture, I have got a few microservices that have to serve REST API for the client but have also to serve grpc request for "internal" purpose, is that a right decision?

A: It is not correct to say "I can't find a way to use a microservice with grpc and HTTP at the same time" since GRPC uses HTTP. GRPC is not a protocol, it is a way to serialize messages, by exposing HTTP endpoints you have the possibility to choose between different alternatives such as XML; REST/JSON or GRPC.
Normally following the "hexagonal architecture" philosophy (https://en.wikipedia.org/wiki/Hexagonal_architecture_(software)) you should be able to separate the logic from the adapters and your project can implement multiple adapters for the same logic, for example one adapter in HTTP/REST and another in HTTP/GRPC. On the other hand, a way to avoid having to implement multiple ports is to always choose HTTP/GRPC and use Envoy as a proxy between HTTP/REST and HTTP/GRPC (see https://grpc.io/docs/tutorials/basic/web/) but final solution depends on many factors


text:
Q: Multipart Form Errors with Lagom Most of our Lagom entrypoints don't use multipart form requests, but one does. Since Lagom doesn't currently support multipart requests natively, the general suggestion I have seen is to call the underlying Play API, using the PlayServiceCall mechanism.
We have done that, and it works--most of the time. But we experience intermittent errors, especially when submitting large files. These are always cases of java.util.zip.ZipException (of various kinds), looking as if not an entire file has been received for processing.
Here's how the entrypoint looks in the code; in particular, the Play wrapping mechanism:
def upload = PlayServiceCall[NotUsed, UUID] {
  wrapCall => Action.async(multipartFormData) {
    request => wrapCall(ServiceCall { _ =>
      val upload = request.body.file("upload")
      val input = new FileInputStream(upload.get.ref.file)
      val filename = upload.get.filename
      // ...
      // other code to actually process the file
      // ...
    })(request).run
  }
}

Here are just two examples of exceptions we're seeing:
Caused by: java.util.zip.ZipException: invalid code lengths set
  at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
  at java.util.zip.ZipInputStream.read(ZipInputStream.java:194)
  at org.apache.poi.openxml4j.util.ZipSecureFile$ThresholdInputStream.read(ZipSecureFile.java:214)
  at java.io.FilterInputStream.read(FilterInputStream.java:107)
  etc.

Caused by: java.util.zip.ZipException: invalid distance too far back
  at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
  at java.util.zip.ZipInputStream.read(ZipInputStream.java:194)
  at org.apache.poi.openxml4j.util.ZipSecureFile$ThresholdInputStream.read(ZipSecureFile.java:214)
  at java.io.FilterInputStream.read(FilterInputStream.java:107)
  etc.

We use Lagom 1.3.8, in Scala. Any suggestions, please?

A: Try using the new service gateway based on Akka HTTP.
You can enable this by adding the following to your build.sbt:
lagomServiceGatewayImpl in ThisBuild := "akka-http"

The new service gateway is still disabled by default in Lagom 1.3.8, but Lagom users that have experienced this problem have reported that it is resolved by enabling the akka-http gateway. This will become the default implementation in Lagom 1.4.0.


text:
Q: Simple QtProject with Cmake: QMainWindow: no such file or directory The simple code I want to run:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
  class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private:
  Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

My CMakeLists.txt:
project(SimpleProject)
# The version number
set (SimpleProject_VERSION_MAJOR 1)
set (SimpleProject_Version_MINOR 0)

cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})

When running in qtcreator it says QMainWindow: No such file or directory
I'm using GCC 4.61 (64 bit) and Qt 4.8.4 (occurs with qt5 also).
So it seems that this has nothing to do with the changes within Qt as I've read somewhere else.
When I try to run a simple Qt sample Application suggested by qtcreator, it works fine. Qt is installed and qtcreator is able to find it. But with CMake it won't.
Do I have to add something to my CMakeLists so that qtcreator is able to locate Qt?

A: I read the documentation and wrote this and it works:
cmake_minimum_required(VERSION 2.8)
PROJECT(SimpleProject)

FIND_PACKAGE(Qt4 REQUIRED)
INCLUDE(${QT_USE_FILE})
ADD_DEFINITIONS(${QT_DEFINITIONS})

SET(SimpleProject_SOURCES main.cpp MainWindow.cpp)
SET(SimpleProject_FORMS MainWindow.ui)
SET(SimpleProject_HEADERS MainWindow.h)

QT4_WRAP_CPP(SimpleProject_HEADERS_MOC ${SimpleProject_HEADERS})
QT4_WRAP_UI(SimpleProject_FORMS_HEADERS ${SimpleProject_FORMS})

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
ADD_EXECUTABLE(SimpleProject
    ${SimpleProject_SOURCES}
    ${SimpleProject_HEADERS_MOC}
    ${SimpleProject_FORMS_HEADERS}
)
TARGET_LINK_LIBRARIES(SimpleProject ${QT_LIBRARIES})