text:
Q: Java Swing -- Writing a Ui that will repaint itself based on changes to a custom data object First things first -- I had posted a question earlier wherein i had asked for help as to why my code was not working and this question is acting upon the advice i got in that question.
My use case is this.
Im writing a MethodEditor module wherein every Method is denoted by a custom data object that has 2 data members --

*

*List of input variable names

*String(name of the result variable that this method sets).

These Method objects are generated as a result of filling out some data on a JDialog.
These Method objects are stored in a container that has 1 data member that is a List<Method>
The container resides in a controller JPanel from where the aforementioned JDialog is invoked.
From a UI perspective I want to display every Method object in the form of a Jbutton on click of which a JDialog will open and allow the user to edit it.

The MethodEditor acts on a List and generated a vertical arrangement of JButtons, 1 for each Method in List<Method>. This List<Method> is passed to the MethodEditor from the aforementioned controller JPane.
I had in my earlier question implemented the MethodEditor as a JPanel that would add a PropertyChangeListener to the List<Method> and would repaint itself everytime there was a PropertyChange event but my approach did not work, the repaint would not happen.
Is there another way to get my use case implemented or is there any fix that i could do to my code posted in the earlier question  ?

A: I'm really lost (from your last three question),
may be, could we imagine that you have got three separated Models for one GUI, in this case doesn't important if you want to change number of elements in the GUI, or change properties for one JComponent,
output from PropertyChangeListener quite guarantee that output could be done on EDT
import java.awt.BorderLayout;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.*;

public class MVC_ProgressBarThread {

    private MVC_ProgressBarThread() {
        MVC_View view = new MVC_View();
        MVC_Model model = new MVC_Model();
        MVC_Control control = new MVC_Control(view, model);
        view.setControl(control);
        JFrame frame = new JFrame("MVC_ProgressBarThread");
        frame.getContentPane().add(view);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                MVC_ProgressBarThread mVC_ProgressBarThread = new MVC_ProgressBarThread();
            }
        });
    }
}

class MVC_View extends JPanel {

    private static final long serialVersionUID = 1L;
    private MVC_Control control;
    private JProgressBar progressBar = new JProgressBar();
    private JButton startActionButton = new JButton("Press Me and Run this Madness");
    private JLabel myLabel = new JLabel("Nothing Special");

    public MVC_View() {
        startActionButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                buttonActionPerformed();
            }
        });
        JPanel buttonPanel = new JPanel();
        startActionButton.setFocusPainted(false);
        buttonPanel.add(startActionButton);
        setLayout(new BorderLayout(10, 10));
        add(buttonPanel, BorderLayout.NORTH);
        progressBar.setStringPainted(true);
        add(progressBar, BorderLayout.CENTER);
        myLabel.setIcon(UIManager.getIcon("OptionPane.questionIcon"));
        myLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        add(myLabel, BorderLayout.SOUTH);
    }

    public void setControl(MVC_Control control) {
        this.control = control;
    }

    private void buttonActionPerformed() {
        if (control != null) {
            control.doButtonAction();
        }
    }

    public void setProgress(int progress) {
        progressBar.setValue(progress);
    }

    public void setProgressLabel(String label) {
        progressBar.setString(label);
    }

    public void setIconLabel(Icon icon) {
        myLabel.setIcon(icon);
    }

    public void start() {
        startActionButton.setEnabled(false);
    }

    public void done() {
        startActionButton.setEnabled(true);
        setProgress(100);
        setProgressLabel("   Done !!!   ");
        setIconLabel(null);
    }
}

class MVC_Control {

    private MVC_View view;
    private MVC_Model model;

    public MVC_Control(final MVC_View view, final MVC_Model model) {
        this.view = view;
        this.model = model;
        model.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent pce) {
                if (MVC_Model.PROGRESS.equals(pce.getPropertyName())) {
                    view.setProgress((Integer) pce.getNewValue());
                }
                if (MVC_Model.PROGRESS1.equals(pce.getPropertyName())) {
                    view.setProgressLabel((String) pce.getNewValue());
                }
                if (MVC_Model.PROGRESS2.equals(pce.getPropertyName())) {
                    view.setIconLabel((Icon) pce.getNewValue());
                }
            }
        });
    }

    public void doButtonAction() {
        view.start();
        SwingWorker<Void, Void> swingworker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                model.reset();
                model.startSearch();
                return null;
            }

            @Override
            protected void done() {
                view.done();
            }
        };
        swingworker.execute();
    }
}

class MVC_Model {

    public static final String PROGRESS = "progress";
    public static final String PROGRESS1 = "progress1";
    public static final String PROGRESS2 = "progress2";
    private static final int MAX = 11;
    private static final long SLEEP_DELAY = 1000;
    private int progress = 0;
    private String label = "Start";
    private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
    private PropertyChangeSupport pcs1 = new PropertyChangeSupport(this);
    private PropertyChangeSupport pcs2 = new PropertyChangeSupport(this);
    private final String[] petStrings = {"Bird", "Cat", "Dog",
        "Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
    private int index = 1;
    private Queue<Icon> iconQueue = new LinkedList<Icon>();
    private Icon icon = (UIManager.getIcon("OptionPane.questionIcon"));

    public void setProgress(int progress) {
        int oldProgress = this.progress;
        this.progress = progress;
        PropertyChangeEvent evt = new PropertyChangeEvent(this, PROGRESS,
                oldProgress, progress);
        pcs.firePropertyChange(evt);
    }

    public void setProgressLabel(String label) {
        String oldString = this.label;
        this.label = label;
        PropertyChangeEvent evt = new PropertyChangeEvent(this, PROGRESS1,
                oldString, label);
        pcs1.firePropertyChange(evt);
    }

    public void setIconLabel(Icon icon) {
        Icon oldIcon = this.icon;
        this.icon = icon;
        PropertyChangeEvent evt = new PropertyChangeEvent(this, PROGRESS2,
                oldIcon, icon);
        pcs2.firePropertyChange(evt);
    }

    public void reset() {
        setProgress(0);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(listener);
        pcs1.addPropertyChangeListener(listener);
        pcs2.addPropertyChangeListener(listener);
    }

    public void startSearch() {
        iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));
        for (int i = 0; i < MAX; i++) {
            int newValue = (100 * i) / MAX;
            setProgress(newValue);
            setProgressLabel(petStrings[index]);
            index = (index + 1) % petStrings.length;
            setIconLabel(nextIcon());
            try {
                Thread.sleep(SLEEP_DELAY);
            } catch (InterruptedException e) {
            }
        }
    }

    private Icon nextIcon() {
        Icon icon1 = iconQueue.peek();
        iconQueue.add(iconQueue.remove());
        return icon1;
    }
}

A: Your problem has been mentioned before as has its solution. You must actually add or remove the component to your observer panel from within the PropertyChangeListener. Calling revalidate() and repaint() will not magically add or remove components unless you explicitly do this before these methods are called.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.IndexedPropertyChangeEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;

public class ListenToTest {
   public static final String[] ITEMS = {"Sunday", "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "Saturday"};
   private JPanel mainPanel = new JPanel();
   private ObserverPanel observerPanel = new ObserverPanel();
   private ListenToModel model = new ListenToModel();

   public ListenToTest() {
      observerPanel.setModel(model);

      for (String item : ITEMS) {
         model.addItem(item);
      }

      JPanel btnPanel = new JPanel();
      btnPanel.add(new JButton(new AddAction("Add")));
      btnPanel.add(new JButton(new RemoveAction("Remove")));

      mainPanel.setLayout(new BorderLayout());
      mainPanel.add(new JScrollPane(observerPanel.getMainComponent()));
      mainPanel.add(btnPanel, BorderLayout.PAGE_END);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private class AddAction extends AbstractAction {
      public AddAction(String title) {
         super(title);
      }

      @Override
      public void actionPerformed(ActionEvent arg0) {
         String text = JOptionPane.showInputDialog(mainPanel, "Enter a String");
         if (text != null) {
            model.addItem(text);
         }
      }
   }

   private class RemoveAction extends AbstractAction {
      public RemoveAction(String title) {
         super(title);
      }

      @Override
      public void actionPerformed(ActionEvent arg0) {
         int index = observerPanel.getSelectedIndex();
         if (index >= 0) {
            model.removeItem(index);
         }
      }
   }

   private static void createAndShowGui() {
      ListenToTest mainPanel = new ListenToTest();

      JFrame frame = new JFrame("ListenToModelTest");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class ObserverPanel {
   public static final Font LABEL_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 18);
   protected static final Color SELECTED_COLOR = new Color(150, 150, 255);
   private JPanel mainPanel = new JPanel();
   private ListenToModel model;
   private GridLayout gridLayout = new GridLayout(0, 1);
   private int selectedIndex = -1;

   public ObserverPanel() {
      mainPanel.setLayout(gridLayout);
      mainPanel.addMouseListener(new MouseAdapter() {
         @Override
         public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            Component[] components = mainPanel.getComponents();
            for (int i = 0; i < components.length; i++) {
               if (mainPanel.getComponentAt(p).equals(components[i])) {
                  selectedIndex = i;
                  components[i].setBackground(SELECTED_COLOR);
               } else {
                  components[i].setBackground(null);
               }
            }
         }
      });
   }

   public int getSelectedIndex() {
      return selectedIndex;
   }

   public void setModel(ListenToModel model) {
      this.model = model;
      model.addPropertyChangeListener(new ObserverPanelListener());
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private class ObserverPanelListener implements PropertyChangeListener {
      public void propertyChange(PropertyChangeEvent evt) {
         if (evt.getPropertyName().equals(ListenToModel.ADD)) {
            JLabel label = createLabel(evt);
            for (Component comp : mainPanel.getComponents()) {
               comp.setBackground(null);
            }
            int index = ((IndexedPropertyChangeEvent)evt).getIndex();
            mainPanel.add(label, index);
            label.setBackground(SELECTED_COLOR);
            selectedIndex = index;
         } else if (evt.getPropertyName().equals(ListenToModel.REMOVE)) {
            int index = ((IndexedPropertyChangeEvent)evt).getIndex();
            mainPanel.remove(index);
            for (Component comp : mainPanel.getComponents()) {
               comp.setBackground(null);
            }
            selectedIndex = -1;
         } else if (evt.getPropertyName().equals(ListenToModel.REMOVE_ALL)) {
            mainPanel.removeAll();
            selectedIndex = -1;
         }
         mainPanel.revalidate();
         mainPanel.repaint();
      }

      private JLabel createLabel(PropertyChangeEvent evt) {
         String newValue = evt.getNewValue().toString();
         JLabel label = new JLabel(newValue);
         label.setFont(LABEL_FONT);
         int eb = 20;
         label.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.blue),
               BorderFactory.createEmptyBorder(eb , eb, eb, eb)));
         label.setFocusable(true);
         label.setOpaque(true);
         return label;
      }
   }
}

class ListenToModel implements Iterable<String> {
   public static final String ADD = "add";
   public static final String REMOVE = "remove";
   public static final String REMOVE_ALL = "remove all";
   private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
         this);
   private List<String> modelNucleus = new ArrayList<String>();

   public void addItem(String item) {
      modelNucleus.add(item);
      spcSupport.fireIndexedPropertyChange(ADD, modelNucleus.size() - 1, null,
            item);
   }

   public void addItem(int index, String item) {
      if (index < 0 || index > modelNucleus.size()) {
         // TODO: throw an exception
      } else {
         modelNucleus.add(index, item);
         spcSupport.fireIndexedPropertyChange(REMOVE, index, null, item);
      }

   }

   public void removeItem(int index) {
      if (index < 0 || index >= modelNucleus.size()) {
         // TODO: throw an exception
      } else {
         String oldValue = modelNucleus.remove(index);
         spcSupport.fireIndexedPropertyChange(REMOVE, index, oldValue, null);
      }
   }

   public void removeAll() {
      modelNucleus.clear();
      spcSupport.firePropertyChange(REMOVE_ALL, null, null);
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      spcSupport.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      spcSupport.removePropertyChangeListener(listener);
   }

   @Override
   public Iterator<String> iterator() {
      return modelNucleus.iterator();
   }
}

A: Please verify that the PropertyChangeEvent does not fire. If it does fire, but the repaint does not happen, it might help to postpone the repaint a bit like this:
//change this
button.repaint();

// to this
SwingUtilties.invokeLater(new Runnable() { public void run() { button.repaint(); }});

If the change event does not fire - disregard all after 'Please' ;)


text:
Q: Missing Play! compiler error page, no data returned Migrated to Play! 2 and been hacking some code, but it's extremely difficult because every time I get a compiler error, I see this page in the browser:

Does anyone know the fix for this and why it would happen? Referencing this email thread looks like others are having trouble, too: https://groups.google.com/forum/?fromgroups#!topic/play-framework/Co9jFkmPYbA
Update: eBean
After further investigation, eBeanPlugin is having trouble loading on every sample app and my own:
play.api.PlayException: Cannot load plugin [Plugin [play.db.ebean.EbeanPlugin] cannot been instantiated.]
What's a possible fix?

A: Was able to resolve the problem. This particular distro of Play! was built from the GitHub repo. The steps I followed to get it working:

*

*Cleaned Play! folder and made backup of project

*Downloaded release binaries from http://www.playframework.org/download

*Created a shiny new project play new myapp

*Imported app, conf, and public folders

Was a pain to figure out, but I hope this helps someone in the future.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assignment-Operator for templated class For clarification, I'm citing James McNellis answer in the post "Template assignment operator overloading mystery":

The implicitly-declared copy assignment operator, which is declared as follows, is still generated:

Wrapper& operator=(const Wrapper&);

Now I have a similar class and would like to know what the definition of this operator needs to look like.
Here's the class for recall:
template<typename T>
struct Wrapper;

What is now the correcting match:
template<typename T>
Wrapper& Wrapper<T>::operator=(const Wrapper&)

or
Wrapper& Wrapper::operator=(const Wrapper&)

?
Or is this just the same?

A: This
template<typename T>
Wrapper& Wrapper<T>::operator=(const Wrapper&)

which is really just shorthand for
template<typename T>
Wrapper<T>& Wrapper<T>::operator=(const Wrapper<T>&)

The other version would apply to a non-template class named Wrapper, it has no effect on your templates.


text:
Q: How to save best model in Keras based on AUC metric? I would like to save the best model in Keras based on auc and I have this code:
def MyMetric(yTrue, yPred):
    auc = tf.metrics.auc(yTrue, yPred)
    return auc

best_model = [ModelCheckpoint(filepath='best_model.h5', monitor='MyMetric', save_best_only=True)]

train_history = model.fit([train_x],
          [train_y], batch_size=batch_size, epochs=epochs, validation_split=0.05,
                          callbacks=best_model, verbose = 2)

SO my model runs nut I get this warning:
RuntimeWarning: Can save best model only with MyMetric available, skipping.
  'skipping.' % (self.monitor), RuntimeWarning)

It would be great if any can tell me this is the right way to do it and if not what should I do?

A: You have to pass the Metric you want to monitor to model.compile.
https://keras.io/metrics/#custom-metrics
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[MyMetric])

Also, tf.metrics.auc returns a tuple containing the tensor and update_op. Keras expects the custom metric function to return only a tensor.
def MyMetric(yTrue, yPred):
    import tensorflow as tf
    auc = tf.metrics.auc(yTrue, yPred)
    return auc[0]

After this step, you will get errors about uninitialized values. Please see these threads:
https://github.com/keras-team/keras/issues/3230
How to compute Receiving Operating Characteristic (ROC) and AUC in keras?

A: You can define a custom metric that calls tensorflow to compute AUROC in the following way:
def as_keras_metric(method):
    import functools
    from keras import backend as K
    import tensorflow as tf
    @functools.wraps(method)
    def wrapper(self, args, **kwargs):
        """ Wrapper for turning tensorflow metrics into keras metrics """
        value, update_op = method(self, args, **kwargs)
        K.get_session().run(tf.local_variables_initializer())
        with tf.control_dependencies([update_op]):
            value = tf.identity(value)
        return value
    return wrapper

@as_keras_metric
def AUROC(y_true, y_pred, curve='ROC'):
    return tf.metrics.auc(y_true, y_pred, curve=curve)

You then need to compile your model with this metric:
model.compile(loss=train_loss, optimizer='adam', metrics=['accuracy',AUROC])

Finally: Checkpoint the model in the following way:
model_checkpoint = keras.callbacks.ModelCheckpoint(path_to_save_model, monitor='val_AUROC',
                                                   verbose=0, save_best_only=True,
                                                   save_weights_only=False, mode='auto', period=1)

Be careful though: I believe the Validation AUROC is calculated batch wise and averaged; so might give some errors with checkpointing. A good idea might be to verify after model training finishes that the AUROC of the predictions of the trained model (computed with sklearn.metrics) matches what Tensorflow reports while training and checkpointing

A: Assuming you use TensorBoard, then you have a historical record—in the form of tfevents files—of all your metric calculations, for all your epochs; then a tf.keras.callbacks.Callback is what you want.
I use tf.keras.callbacks.ModelCheckpoint with save_freq: 'epoch' to save—as an h5 file or tf file—the weights for each epoch.
To avoid filling the hard-drive with model files, write a new Callback—or extend the ModelCheckpoint class's—on_epoch_end implementation:
def on_epoch_end(self, epoch, logs=None):
    super(DropWorseModels, self).on_epoch_end(epoch, logs)
    if epoch < self._keep_best:
        return

    model_files = frozenset(
        filter(lambda filename: path.splitext(filename)[1] == SAVE_FORMAT_WITH_SEP,
               listdir(self._model_dir)))

    if len(model_files) < self._keep_best:
        return

    tf_events_logs = tuple(islice(log_parser(tfevents=path.join(self._log_dir,
                                                                self._split),
                                             tag=self.monitor),
                                  0,
                                  self._keep_best))
    keep_models = frozenset(map(self._filename.format,
                                map(itemgetter(0), tf_events_logs)))

    if len(keep_models) < self._keep_best:
        return

    it_consumes(map(lambda filename: remove(path.join(self._model_dir, filename)),
                    model_files - keep_models))

Appendix (imports and utility function implementations):
from itertools import islice
from operator import itemgetter
from os import path, listdir, remove
from collections import deque

import tensorflow as tf
from tensorflow.core.util import event_pb2

def log_parser(tfevents, tag):
    values = []
    for record in tf.data.TFRecordDataset(tfevents):
        event = event_pb2.Event.FromString(tf.get_static_value(record))
        if event.HasField('summary'):
            value = event.summary.value.pop(0)
            if value.tag == tag:
                values.append(value.simple_value)

    return tuple(sorted(enumerate(values), key=itemgetter(1), reverse=True))

it_consumes = lambda it, n=None: deque(it, maxlen=0) if n is None \
                                 else next(islice(it, n, n), None)

SAVE_FORMAT = 'h5'
SAVE_FORMAT_WITH_SEP = '{}{}'.format(path.extsep, SAVE_FORMAT)

For completeness, the rest of the class:
class DropWorseModels(tf.keras.callbacks.Callback):
    """
    Designed around making `save_best_only` work for arbitrary metrics
             and thresholds between metrics
    """

    def __init__(self, model_dir, monitor, log_dir, keep_best=2, split='validation'):
        """
        Args:
            model_dir: directory to save weights. Files will have format
                        '{model_dir}/{epoch:04d}.h5'.
            split: dataset split to analyse, e.g., one of 'train', 'test', 'validation'
            monitor: quantity to monitor.
            log_dir: the path of the directory where to save the log files to be
                        parsed by TensorBoard.
            keep_best: number of models to keep, sorted by monitor value
        """
        super(DropWorseModels, self).__init__()
        self._model_dir = model_dir
        self._split = split
        self._filename = 'model-{:04d}' + SAVE_FORMAT_WITH_SEP
        self._log_dir = log_dir
        self._keep_best = keep_best
        self.monitor = monitor

This has the added advantage of being able to save and delete multiple model files in a single Callback. You can easily extend with different thresholding support, e.g., to keep all model files with an AUC in threshold OR TP, FP, TN, FN within threshold.


text:
Q: How to make a program wait for a lock on a sqlite database I have a program that runs as part of a larger process with the sole purpose being to safely copy a sqlite database to another folder for back-up.  Only problem is that my production run just went down because the database was locked by other processes.  Is there a way I can specify for this program to wait to obtain a lock?  It is okay if it holds up the rest of the program by a few seconds.
Here is my code:
import sqlite3
import shutil
import optparse
import os
import time
import logging

logging.basicConfig(level=logging.INFO, format="[%(levelname)s] - %(message)s")
logging.disable(logging.CRITICAL)

def sqlite3_backup(db_file, backup_dir):
    print 'DB is: ', db_file + '\n', 'Backup Dir is: ', backup_dir
    if not os.path.isdir(backup_dir):
        raise Exception("Backup directory does not exist: {0}".format(backup_dir))

    with sqlite3.connect(db_file) as conn:
        logging.info('Connected to the database.')
        cursor = conn.cursor()
        cursor.execute('begin immediate')
        shutil.copy(db_file, backup_dir)
        logging.info('Closing the database.')

usage = "%prog [options] db-file backup-dir"
description = """\
Backup sqlite3 database to a directory, appending a datestamp on the backup."""

def get_options():
    parser = optparse.OptionParser(usage=usage, description=description)
    opts, args = parser.parse_args()
    if len(args) != 2:
        raise parser.error("Incorrect number of parameters")

    opts.databasefile, opts.backupdir = args
    return opts

if __name__ == '__main__':
    opts = get_options()
    sqlite3_backup(opts.databasefile, opts.backupdir)

A: if __name__ == '__main__':
    opts = get_options()
    for i in range(90): #give up after 90 seconds
        try:
            sqlite3_backup(opts.databasefile, opts.backupdir)
        except sqlite3.OperationalError as e:
            if "locked" in str(e):
                 time.sleep(1)
            else:
                 raise
        else:
            sys.stdout.write("OK Backup sucess!")
            sys.exit(0)
   sys.stderr.write("Unable to aquire database lock...")
   sys.exit(1)

Is one way you might do this ...
I would also recommend using an ORM as I think most ORM's may implement this sort of thing for you behind the scenes (maybe im wrong)


text:
Q: Is there a way to make the data loaded from the d3.csv function global? Ok, big disclaimer: I'm a novice programmer, and this is my first time ever with javascript and d3.js.
I'm working on a project using d3.js. I have 100 datasets(all stored locally in a folder) of different cryptocurrencies, and I'd like to build graphs to study them.
I've implemented nice functions to draw interactive graphs and to preprocess data. Everything works just fine as long as I decide to work with a single dataset.
Why? Because I'm basically doing all the things that I'd like to do with my data inside the callback of the d3.csv(path,callback(data){...}).
Since I'd like to change dynamically the datasets(a.k.a. the path), for example with a dropdown menu, I'd like to have a way to load the csv like I'd do in python:
with open('testfile.csv', newline='') as csvfile:
    data = list(csv.reader(csvfile))

I thought that a possible solution would have been to create a global variable and filling it with the preprocessed data inside the callback... but if I try to print or to use in any way these data inside the global variable, this is not working(I readed every stackoverflow post about this and I'm 99.9% saying that it's an asynchronicity issue)(check snippet of code down here).
// SNIPPET OF CODE THAT IT DOES **NOT** WORK

var my_global_variable = {"name": keyword,"date": [], "high": [],"low": [],"market cap": [],"open": [],"close": [],"volume": []};

 var _data_ = d3.csv(path, function(data) {
      my_global_variable = FunctionToProcessData(data)
    })
console.log(my_global_variable)

The print I get is the following(sorry,not enough reputation on SO for posting an image):
{name: "Dogecoin", date: Array(0), high: Array(0), low: Array(0), market cap: Array(0), …}

But it's weird because if I click the dropdown arrow on the console of my browser where I'm running the code, even though here it is written that each array inside the keys of my_global_variable is empty( 0), after clicking it I WILL SEE ELEMENTS, like if they get created only when I specifically requested it:
{name: "Dogecoin", date: Array(0), high: Array(0), low: Array(0), market cap: Array(0), …}
  close: (1378) ["0.000772", "0.000755", "0.000862",  …]
  date: (1378) [Fri Sep 22 2017 00:00:00 GMT+0200 (Ora legale dell'Europa centrale), …]
  market cap: (1378) ["84749600", "94429700", "97923500", …]
  name: "Dogecoin"
  open: (1378) ["0.000762", "0.00085", "0.000881", …]
  volume: (1378) ["3758470", "3157030", "4641920",  …]
  __proto__: Object

I'm not an expert of javascript: is there a way to load data from a local folder and use them as I would do simply in python? A.K.A. : Can anyone give me a solution for this?
I report here my code to clear any possible doubt:
HTML FILE:
   <!DOCTYPE html>
    <head>
    <meta charset="utf-8">
    <script src="https://d3js.org/d3.v4.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
    <script src="test.js" defer></script>
    </head>
    <body>
        <div id="my_dataviz">
        </div>
    </body>

Javascript test.js file:
var keyword = "Dogecoin";
var path = `archive/${keyword}.csv`;

var data_final = {"key": keyword,"values": []}

var svg = d3.select("#my_dataviz").append("svg").attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom).append("g").attr("transform","translate(" + margin.left + "," + margin.top + ")").attr("id", 1)

var margin = {top: 10, right: 30, bottom: 30, left: 60},

width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;

var _data_ = d3.csv(path, function(data) {
  data_final = FunctionToProcessData(data)
  draw_time_chart(svg,margin,data_final,attr)
})

function FunctionToProcessData(data){
 // do stuff with my data.
 // It's quite long and not the point of this question,
 // so I won't copypaste it here

 return data_final
}

function draw_time_chart(svg,margin,data_final,attr){
     // do stuff to draw a graph with my data.
     // It's quite long and not the point of this question,
     // so I won't copypaste it here
}

P.S. Yes,I have already checked d3: make the d3.csv function syncronous , but this didn't solve my issue.


text:
Q: SAP IQ: Export to Client-Side Is there a way to Export the tables from Sybase IQ 16 to flat files saved locally on my Client?
I can use Unload or Output to from ISQL to save it Server side but didn't find a solution for Client-Side file.
It would be fine also when it's not just usable in ISQL
Someone know a solution? :)
thx in advance

A: This should be possible by using dbisql via Data->Export giving you are able to run it manually.


text:
Q: sort column by date TbJSONGridView I want to sort a column in TbJSONGridView by date , I have this code
$this->widget(
        'bootstrap.widgets.TbJsonGridView', array(
    'dataProvider' => $model->searchPending(),
    'type' => 'striped bordered condensed',
    'summaryText' => false,
    'cacheTTL' => 10, // cache will be stored 10 seconds (see cacheTTLType)
    'cacheTTLType' => 's', // type can be of seconds, minutes or hours
    'enablePagination' => true,
    'columns' => array(
 array(
            'name' => 'Pickup Date',
            'value' => '$data->carShippeds[0]->pickup_date',
            'type'=>'date',
        ),
))

but the column I get it is from a related model, and the sorting is not working, when I clicked on the column header it does nothing.
what's wrong with the code???
Gabriel

A: $data->carShippeds[0]->

This shows us that the current model has many cars shipped. You are only showing the first one in there. While that works, Yii has no way of knowing that you are only showing the first value so your sorting has no chance of working. Create a view that only selects your first pickup date, make a join in your criteria with the main model, show the field without [0]-> and it will work.

A: Change the below section:
array(
     'name' => 'Pickup Date',
     'value' => '$data->carShippeds[0]->pickup_date',
     'type'=>'date',
),

To this:
array(
     'name' => 'pickup_date',
     'header' => 'Pickup Date',
     'value' => '$data->carShippeds[0]->pickup_date',
     'type'=>'date',
),

Then in your 'form' when you want to return DataProvider write the specific sorting code for this association like below:
return new DataProvider($query, [
            'pagination' => [
                'pagesize' => 20,
            ],
            'sort' => [
                'sortVar' => 'sort',
                'defaultOrder' => ['t.carShippeds.pickup_date asc'],
                'attributes' => [
                    'pickup_date' => [
                        'asc' => 't.carShippeds.pickup_date',
                        'desc' => 't.carShippeds.pickup_date DESC',
                    ],
                    '*',
                ],

            ],
]);

Please notice that I did not know the join alias you have for your t.carShippeds or even whether it is t or another entity. replace it or give me more information about your DataProvider and I can help more.


text:
Q: Take variables from define function in python I have a question on extracting variables in def
For example,
def func(z,W):
    A = z[1]
    B = z[2]
    C = z[3]
    Var = k*B/C
    dAdW = A*3
    dBdW = B*2/Var
    dCdW = C**2*Var**2
    return dAdW, dBdW, dCdw
init = [0,0,1]
W = np.linspace(0,100,1000)
sol = odeint(func, init, W)
plt.plot(W,sol[:,0])
plt.plot(W,Var) # ----> this one

Since Var is not a differential equation,
I can't declare Var as Var = z[4]
I tried using global but it only yields the last value.
How do I get all the values of Var in an array so I can plot the Var?
k is a constant like 1
Thank you for taking a look into this!
Here is a full code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

alpha = 0.0002
Uapb = 0.5
deltaH = -20000
Cpa = Cpb = 20
Cpi = 40
Ea = 25000
Kc1 = 100 # @ T=303
k1 = 0.004 #@ T=310K
CPcool = 20
Fao = 5
Cao = 1
mc = 1000
R = 1.987
To = 330

def func(z,W):
    pbar = z[0]
    X = z[1]
    Ta = z[2]
    T = z[3]
    k = k1*np.exp(Ea/R*(1/310-1/T))
    Kc = Kc1 * np.exp(deltaH / R * (1 / 303 - 1 / T))
    Ca = Cao * (1 - X) * To / T * pbar
    Cb = Cao*(1-X)*To/T*pbar
    Cc = 2*Cao*To/T*pbar
    Ci = To/T*pbar
    ra = k*(Ca*Cb-Cc**2/Kc)
    dxdw = -ra/Fao
    dpbardw = -alpha/(2*pbar)*T/To
    dTadw = (Uapb)*(T-Ta)/(mc*CPcool)
    dTdw = (Uapb*(Ta-T)+ra*deltaH)/(Fao*(Ca+Cb+Ci))
    return dxdw, dpbardw, dTadw, dTdw

init = [1, 0, 320, 320]
W = np.linspace(0,4500,1000)

sol = odeint(func, init, W)
#Xe = (2 * Kc - ((2 * Kc) ** 2 - 4 * Kc * (Kc - 4)) ** (1 / 2)) / (2 * (Kc - 4))
plt.plot(W, sol[:,0])
#plt.plot(W, Xe)

A: To capture the data from each call, you can do something like this:
capture_var = []

def func(z,W):
    Var = ...

    global capture_var
    capture_var.append(Var)

Please note: that this is rather a hack, and if you doing some basic scripting to solve some small problems is likely fine.  However, if you are working on a code base of any size, please don't do this sort of thing, as these sorts of practices can be a maintenance nightmare.


text:
Q: error: checksum failure file: sources/expat-2.1.0.tar.gz I am try to download RTEMS source builder and build a tool chain following the instruction in this page. The problem that I have seems to be a package download automatically through sourceforge.net: it seems that the chacksum is different. Here the hot part of the log file:
source setup: expat-2.1.0-x86_64-linux-gnu-1: source expat -q -n expat-2.1.0
making dir: /home/leonardo/development/rtems/rsb/rtems/sources
download: (full) http://downloads.sourceforge.net/project/expat/expat/2.1.0/expat-2.1.0.tar.gz -> sources/expat-2.1.0.tar.gz
download: http://downloads.sourceforge.net/project/expat/expat/2.1.0/expat-2.1.0.tar.gz -> sources/expat-2.1.0.tar.gz
 redirect: https://downloads.sourceforge.net/#!/project/expat/expat/2.1.0/expat-2.1.0.tar.gz
 redirect: https://downloads.sourceforge.net/#!/project/expat/expat/2.1.0/expat-2.1.0.tar.gz
checksums: expat-2.1.0.tar.gz:  7a07d3f7cca5c0b38ca811984ef8da536da32932d68c1a6cce33ec2462b930bf => 823705472f816df21c8f6aa026dd162b280806838bb55b3432b0fb1fcca7eb86
warning: checksum error: expat-2.1.0.tar.gz
error: checksum failure file: sources/expat-2.1.0.tar.gz

Any idea on how to solve the problem?

A: Try downloading the tar file directly from the link and move the downloaded file to /rtems-source-builder/rtems/sources


text:
Q: Browser starts downloading and opening hundreds of tabs when I try to run my php scripts I tried to include my first php script in one of my html docs.  The code is below.
<?php
$dir="pictures";
$listOfPictures = scandir($dir);

for($i=2; $i<count($listOfPictures); $i++){
    echo "<img src=\"pictures/" . $listOfPictures[$i] .
    "\" alt=\"picture\" height=\"250px\" width=\"150px\"" .
    "onclick=\"showImage(this.src, 'pictures/" .
    $listOfPictures[$i] . "');\"/>\n";
}
?>

When I first tried to open the .html.php file it started opening hundreds of tabs and storing the html doc hundreds of times in my /tmp directory.  I thought it was my code at first so I reduced the loop to only 10 times (the size of that array is about 500) thinking that was the problem.  It just did it again.  So then I created a basic php script like below.
 <!DOCTYPE html>
 <html>
 <body>

 <?php
    echo 'Hello world';
 ?>
 </body>
 </html>

And it still did it.  Any suggestions? Any details I need to add? Thanks in advance.
Edit: I can run php programs fine from the command line.  The above script outputs exactly what I expect.  I am running apache on arch linux.

A: I suspect what's happening is this:
When you double click the file your browser tries to open it, not knowing how to process PHP extension it tries to open it as-if it were a downloaded file. I assume the default software to open a PHP is your browser. This happens repeatedly in a loop.
To get Apache to open it, open a tab in your web browser normally and go to http://localhost/index.php
(I assume here that your file is called index.php and is in whatever is set for your Apache's DocumentRoot).


text:
Q: Running a java.class file from Linux command line - Oracle JDK8 Installed - openJDK removed So, I have removed openjdk from my new Ubuntu system and have installed Oracle JDK 8 and Eclipse from their respective websites. I can run a program from Eclipse, however I cannot run it from the command line. I am also not used to using Eclipse (I use NetBeans for my Java class in college.) I noticed that there is no build button in Eclipse. With all of that being said, here is my command line code:
wil@wil-Aspire-E5-521:~/eclipse-workspace/wiltest/src/wiltest$ ls
test.class  test.java
wil@wil-Aspire-E5-521:~/eclipse-workspace/wiltest/src/wiltest$ java wiltest.test.java
Error: Could not find or load main class wiltest.test.java
wil@wil-Aspire-E5-521:~/eclipse-workspace/wiltest/src/wiltest$ java wiltest.testError: Could not find or load main class wiltest.test
wil@wil-Aspire-E5-521:~/eclipse-workspace/wiltest/src/wiltest$ java test
Error: Could not find or load main class test
wil@wil-Aspire-E5-521:~/eclipse-workspace/wiltest/src/wiltest$

A: You need to add the -classpath . command line option.
You can learn more about classpaths here
I believe the command java -classpath . test might work, but it really depends on a number of items that are better explained in the link above.

A: I actually answered part of my question myself. (For anybody wondering, the classpath is set to be in present working directory by default.) Anyways, I was running java wiltest.test from src and not bin. However, I ran from binary file and it worked. BUT I deleted the .class file thinking that I could change the source file, recompile using javac, and it would create another test.class in the binary folder. It did not. -sigh-


text:
Q: perl date calculation with dates of the format 2012-02-03 00:00:00 I need some help with date calculations in perl with dates for the format "2012-02-03 00:00:00". In particular is there a tool I could use to just increment the days and it switches to month and year correctly? Thanks.

A: See DateTime.
#!/usr/bin/env perl
use strict; use warnings;

use DateTime;

my $ts = '2012-02-03 00:00:00';
my ($y, $m, $d) = ($ts =~ /([0-9]{4})-([0-9]{2})-([0-9]{2})/);
my $dt = DateTime->new(year => $y, month => $m, day => $d);
$dt->add( months => 2, days => 3 );

print $dt->strftime('%Y-%m-%d %H:%M:%S'), "\n";

It's actually a little cleaner to use a DateTime::Format class, and you get error checking for free.
use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
   pattern   => '%Y-%m-%d %H:%M:%S',
   time_zone => 'local',
   on_error  => 'croak',
);

my $ts = '2012-02-03 00:00:00';
my $dt = $format->parse_datetime($ts);
$dt->add( months => 2, days => 3 );
print $format->format_datetime($dt), "\n";

A: The Time::Piece module is a standard part of the Perl installation and probably does all that you need.
This program uses your example date and adds two months and three days, then a further 400 days. Two alternative ways of displaying the values are shown
use strict;
use warnings;

use Time::Piece;
use Time::Seconds 'ONE_DAY';

my $format = '%Y-%m-%d %H:%M:%S';

my $dt = Time::Piece->strptime('2012-02-03 00:00:00', $format);
$dt = $dt->add_months(2);
$dt += 3 * ONE_DAY;

print $dt->strftime($format), "\n";

$dt += 400 * ONE_DAY;

printf "%s %s\n", $dt->ymd, $dt->hms;

output
2012-04-06 00:00:00
2013-05-11 00:00:00

A: This is all perfectly possible within core using the POSIX time-handling functions.
The standard POSIX::mktime function already copes with denormalised values, and can correct for days/months out of range. Additionally, POSIX::strftime actually calls this on the given values before formatting them, so it will adjust correctly.
use POSIX qw( strftime mktime );
use POSIX::strptime qw( strptime );

my $format = "%Y-%m-%d %H:%M:%S";

my @t = strptime( "2012-02-03 00:00:00", $format );
@t = @t[0..5]; # Throw away wday and yday

$t[3] += 3; # mday
$t[4] += 2; # mon

say strftime $format, @t;

$t[3] += 400; # mday

say strftime $format, @t;

Gives
2012-04-06 00:00:00
2013-05-11 00:00:00


text:
Q: Cannot forward after response has been committed - Servlet I am trying to logout from the HTTPSession and redirect the user to the login page.
Below is my complete Http servlet code as is.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
    super.doGet(req, resp);
    processRequest(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
    super.doPost(req, resp);
    processRequest(req, resp);
}

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    final HttpSession session = request.getSession(false);
    if (session != null)
    {
        session.invalidate();
    }

    response.sendRedirect("/login.html");
    //getServletContext().getRequestDispatcher("/login.html").forward(request, response);
}

}
But getting the below exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:339)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.controller.LogoutServlet.processRequest(LogoutServlet.java:41)

A: Remove calls to
super.doGet(req, resp); // and
super.doPost(req, resp);

The Base class implementations simply try to throw an error message that GET or POST is not supported.
// HttpServlet#doGet() calls
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);

The above line is what has already committed the response.

A: Why don't you redirect instead of forward?
    response.sendRedirect("/login.html");


text:
Q: How to block a pcap pumped by tcpreplay from one server by iptables on the other? I am new to stack exchange.
What I am trying is:
I am pumping traffic from one server by the following command:
tcpreplay -i ens3 ~/daniel/sipdump.pcap from server 1
And I am capturing the traffic in the server 2 by tcpdump -i ens3 -nn
I want to block all SIP traffic which uses 5060 by default as source or destination.
But the ip in the pcap is not destination ip:
My server 2 ip is different(192.168.101.5). As I am pumping a pcap the ips are different(source and destination).
[root@serevr1]# tshark -r outbound_incoming1.pcap

  1          0 172.16.130.119 -> 172.16.130.119 SIP/SDP 561 Request: INVITE sip:sandeep@com:5060 |
  2          0 172.16.130.119 -> 172.16.130.119 SIP 358 Status: 100 OK |
  3          0 172.16.130.119 -> 172.16.130.119 SIP 358 Status: 183 OK |
  4          0 172.16.130.119 -> 172.16.130.119 SIP 439 Request: PRACK sip:sandeep@com:5060 |
  5          0 172.16.130.119 -> 172.16.130.119 SIP 364 Status: 200 OK |
  6          0 172.16.130.119 -> 172.16.130.119 SIP 364 Status: 180 OK |
  7          3 172.16.130.119 -> 172.16.130.119 SIP/SDP 529 Status: 200 OK |
  8          3 172.16.130.119 -> 172.16.130.119 SIP 398 Request: ACK sip:sandeep@com:5060 |
  9          6 172.16.130.119 -> 172.16.130.119 SIP 385 Request: BYE sip:kapil@com:5060 |
 10          6 172.16.130.119 -> 172.16.130.119 SIP 346 Status: 200 OK |

I want to drop/accept the sip traffic which are the udp packets in iptables which I am not able to do so.
Please help me out to do so.

A: Try using tcpreplay-edit to modify the destination MAC and destination IP to match your destination server. Or you can use tcprewrite (also part of Tcpreplay suite) to modify the destination MAC/IP of your PCAP file. Either way, your server will reject any traffic all other traffic (except broadcast packets).
Note that if the target is a TCP application, simply changing the MAC and IP address is not sufficient. During TCP handshake, random sequence number are negotiated by client and server, so just pushing a PCAP file will not suffice. In those cases you may be able to use tcpliveplay, but that will require a very specially crafted PCAP file.


text:
Q: How to set file associations and explorer options in one go? This has been itching me for quite a long time.
When I come on a new computer with any version of Windows, I need to:

*

*un-hide file extensions

*set explorer default view to list instead of icons

*set the file extensions like h c cpp so they don't open Visual C++ (which can take up to 20 seconds!) each time I double click on them, opening them with something like Notepad++ instead.

Isn't there some program to quickly set thoses options to something I want, like some standalone exe, or some generic registry file I can execute when I come on a new machine?
I'm a developer and I can't believe I'm wasting so much time on those &*$%@# things.

A: You can do this all through the registry:
Unhide file extensions for known filetypes
You can use the following DWORD to make the file extensions visible:
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"HideFileExt"=dword:00000000

Setting the default Explorer view to 'List'
Setting default explorer view is somewhat more difficult, I always have it in my options when nLiting (you might want to look into nLite, it can automate a lot of stuff during installation and set system settings like the ones you describe).
I assume this key will work (taken straight from my registry), but assuming it doesn't make sure to back up your existing value for Settings first.
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Streams]
"Settings"=hex:08,00,00,00,04,00,00,00,01,00,00,00,00,77,7e,13,73,35,cf,11,ae,\
69,08,00,2b,2e,12,62,04,00,00,00,01,00,00,00,43,00,00,00

Automatically opening certain filetypes in Notepad++
Now, for the automatic opening in Notepad++ go to these keys (or create them):
[HKEY_LOCAL_MACHINE\Software\Classes\.h]
[HKEY_LOCAL_MACHINE\Software\Classes\.c]
[HKEY_LOCAL_MACHINE\Software\Classes\.cpp]

And then create/modify the default string (look at the other keys in Classes to see the way it is done).
This registry file should handle your specific needs:
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"HideFileExt"=dword:00000000

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Streams]
"Settings"=hex:08,00,00,00,04,00,00,00,01,00,00,00,00,77,7e,13,73,35,cf,11,ae,\
69,08,00,2b,2e,12,62,04,00,00,00,01,00,00,00,43,00,00,00

[HKEY_LOCAL_MACHINE\Software\Classes\.h]
@="nppfile"

[HKEY_LOCAL_MACHINE\Software\Classes\.c]
@="nppfile"

[HKEY_LOCAL_MACHINE\Software\Classes\.cpp]
@="nppfile"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\nppfile\DefaultIcon]
@=hex(2):25,00,50,00,72,00,6f,00,67,00,72,00,61,00,6d,00,46,00,69,00,6c,00,65,\
  00,73,00,25,00,5c,00,4e,00,6f,00,74,00,65,00,70,00,61,00,64,00,2b,00,2b,00,\
  5c,00,6e,00,6f,00,74,00,65,00,70,00,61,00,64,00,2b,00,2b,00,2e,00,65,00,78,\
  00,65,00,00,00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\nppfile\shell\open\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
  00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,4e,00,4f,00,\
  54,00,45,00,50,00,41,00,44,00,2e,00,45,00,58,00,45,00,20,00,25,00,31,00,00,\
  00


text:
Q: Visual Studio Cannot Run Project In VS Professional 2019 when I attempt to start my WPF Windows project with debugging I get an error message that says "Error while trying to run project. Access is Denied". Then McAfee LiveSafe AV pops up a message warning me that it's found "Real Protect-LS!B1465A32DC7D" virus and blocks the .EXE file in the debug folder.
When I use McAfee to "restore" the .EXE file, then scan the whole project folder; the AV says no viruses found. Other projects I'm working on are fine.
I found one SO article that suggests to turn on native debugging, but that made no difference. I searched Google for the virus name and most links talk about it as being a false positive.
Does anyone know how to fix this? My dev work has ground to a halt!


text:
Q: get two recent files from a folder in a batch script I am trying to write a batch script that gets two recent files based on creation time from a given directory. In this batch script i want to invoke an .exe file that takes these two files as arguments.
Can someone please help me with this.
dir /a:-d-s /b /o:-d /t:c

This is the command i used that would list the names of the files in descending order based on the creation time. The command prints the result to the console but i want to assign it to some variable or array and access the top two filenames.

A: The following example is intended to set the two topmost returned files as 'array type' variables %Newest[1]% and %Newest[2]%
@For /F "Delims==" %%A In ('Set Newest[ 2^>NUL')Do @Set "%%A="
@For /F "Tokens=1*Delims=:" %%A In ('Dir /B/A-D-S/O-D/TC 2^>NUL^|FindStr /N "^"'
)Do @If %%A LEq 2 (Set "Newest[%%A]=%%B")Else GoTo Next
:Next
@Set Newest[ 2>NUL&&Pause

The last line was included just to show you any variables created from the loop. You would obviously replace this line with your own code, or leave it as is, and place your code beneath it. If you want to use the most recently modified date and time stamps instead of created, replace /TC with /TW on line 2

Off-topic:
Here's an example of it in use, based upon your later posted question, since deleted:

@Echo Off
For /F "Delims==" %%A In ('Set Newest 2^>NUL')Do Set "%%A="
For /F "Tokens=1-2*Delims=:" %%A In ('Dir /B/A-D-S/O-D/TC "Checkpoints" 2^>NUL^
 ^|FindStr /N "^"')Do If %%A LEq 2 (Set "Newest%%A=%%B")Else GoTo Next
:Next
Set "DT1="&For /F "Tokens=1*Delims=_" %%A In ('Set Newest 2^>NUL'
)Do If Not Defined DT1 (Set "DT1=%%~nB")Else Set "DT2=%%~nB"
If Not Defined DT1 Exit /B
Set "Target=Differences\Difference_%DT1%_%DT2%.csv"
Set Newest 2>NUL
Set Target 2>NUL
If Not Exist "Differences\" MD "Differences"
Pause

A: Here is a commented batch file for this task.
@echo off
rem Set up a local environment for this batch file with enabled command
rem extensions as required for command FOR and with disabled delayed
rem environment variable expansion to process also correct file names
rem with one or more exclamation marks in name.
setlocal EnableExtensions DisableDelayedExpansion

rem Make directory of the batch file the current directory.
rem It is possible to use any other directory on replacing
rem %~dp0 by a directory path.
pushd "%~dp0"

rem Make sure the environment variable File1 is not defined.
set "File1="

rem Get a list of files without system attribute in current directory
rem ordered by creation date with newest first and oldest last and process
rem this list of file names line by line with ignoring the batch file. The
rem loop processing the file names is exited after having assigned second
rem newest created file in this directory to the environment variable File2
rem in addition to newest file assigned to environment variable File1 with
rem a jump to the command line below the line with label RunProgram.
for /F "eol=| delims=" %%I in ('dir /A-D-S /B /O-D /TC 2^>nul') do (
    if not "%%I" == "%~nx0" (
        if not defined File1 (
            set "File1=%%I"
        ) else (
            set "File2=%%I"
            goto RunProgram
        )
    )
)

rem There is no file or just one file found in current directory other
rem than this batch file and so the program cannot be executed at all.
goto EndBatch

rem Run the program with the file names of the two newest
rem created files in current directory (batch file directory).
:RunProgram
"C:\Path To Application\Application.exe" "%File1%" "%File2%"

rem Restore the initial current directory and also the initial environment
rem variables list on starting of this batch file as well as initial state
rem of command extensions and delayed environment variable expansion.
:EndBatch
popd
endlocal

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*call /? ... explains %~dp0 (drive and path of batch file) and %~nx0 (name and extension of batch file).

*dir /?

*echo /?

*endlocal /?

*for /?

*goto /?

*if /?

*popd /?

*pushd /?

*rem /?

*set /?

*setlocal /?
Read the Microsoft article about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background with %ComSpec% /c and the specified command line appended.


text:
Q: Machine Learning - Information extraction from a document I'm trying to train a couple of neural networks (using tensorflow) to be able to extract semantic information from invoices. After a long list of reading I came up with this:

*

*Use word2vec to generate word embeddings (more on the corpus below).

*Feed the output of word2vec to a CNN since vectors that are close together share similar semantic meanings.

So the very high level approach I described above seems quite alright to me. I would love for it to be corrected if anything looks wrong.
A couple of concerns that I have:

*

*Corpus selection. Is it sufficient to use a generic corpus of, for instance, wikipedia? Or should I use a specialized corpus for invoices? If it's the latter, how can I generate this corpus? I do have a big dataset of invoices that I can utilize.

*Information extraction. Let's say all of the above work fine and I'm able to understand semantic information from a new unseen invoice. How do I go about extracting certain pieces of information? For instance, let's say we introduce a new invoice that has order number: 12345, assuming order number is understood to be the invoice number (or whatever vectors that lie in the same vicinity of order number), how do I extract the value 12345? One area I was looking at is SyntaxNet that could help here.

Any help/insight is appreciated.
Follow up to @wasi-ahmad's question:
The reason I'm trying to understand semantic information about an invoice is to ultimately be able to extract values out of it. So, for instance, if I present an unseen invoice to my neural network it would find the invoice's number (whatever its label is called) and extract its value.

A: *

*If you have big dataset of invoices, its better you use that. Dataset has some obvious impact on word embeddings construction. To construct the corpus, you can remove common stop words (like a, the etc.) and then use tf-idf weight of each word to represent a document before feeding them to a skip-gram or CBOW model. You can also use one-hot encoding as an alternative of tf-idf weight. You can also think about simple language model (using bigram or trigram) since you have a very specific domain to work on. This would make your model more simpler!

*Your second concern is not clear to me! Usually numeric values are replaced by some label, say NUM during pre-processing step in information extraction task. However, SyntaxNet is actually for dependency parsing. Since your ultimate goal is to extract semantic meaning from invoices, why you need syntactical information? Is it going to help you in this task? If you have a large dataset, you can generate a dictionary for the specific targeted domain. But it depends on how you are going to use the extracted semantic information which you didn't mention in your post!
This is my personal opinion (not aiming to criticize you) that use of word embedding or neural network based models everywhere is not feasible. Word embedding or neural network based approaches give good performance in return of heavy computational complexity. So, if you can serve your purpose with a simple and efficient model, why would you prefer a complex and computationally expensive model? You must have very good reasoning about your chosen model. It is not a wise decision to use a model only because the model is popular and widely used.

A: I am assuming this is a straight forward extraction problem for invoices. You are proposing a way more complex solution than probably needed--I don't really see how it could work but I don't know everything. Let's step back and start simple:
1) Take at least one example of each type of invoice you expect to process and mark it up with xml like tags that mirror the goal extraction e.g. "Order Number: 12445". XML or other parser can grab it later for the evaluation step if needed or post processing.
2) Think of the simplest way to extract the information--I suggest you start with a regular expression matcher.
3) If a regex matcher is insufficient then you may need some supervised machine learning. This will be able to get more varied phrases and can perform at a very high level of precision and recall for the right phrases. See http://alias-i.com/lingpipe/demos/tutorial/ne/read-me.html for a bunch of approaches.
4) If you need more than phrase matching--e.g. part number and part count then you may need to top the stack with a classifier that decides whether the concurrence is legit or not.
Hope that helps.
Breck


text:
Q: VBA in access...IF THEN ELSE I am trying to make a conditional statement that will basically say if field1 + field2 = "string" then do some stuff... i am pretty sure i have the stuff part right but i dont think i have the conditional statement correct... this is what i have
txtTeam.Visible = True
If ([GuestFirstName] + [GuestLastName] = "Angela Cockrill") Then
    [LifetimeTxt] = "Trips of a Lifetime!"
    txtTeam.ForeColor = vbOrange
    txtTeam.FontSize = 14
    txtTeam.FontBold = True

Else
    txtTeam.Visible = False
    txtTeam.ForeColor = 0

End If

A: In MS Access VBA I would use the ampersand operator & to concatenate 2 strings together, not the plus sign but that's just a preference. You also may need to account for the space e.g.
txtTeam.Visible = True
If ([GuestFirstName] & " " & [GuestLastName] = "Angela Cockrill") Then
    [LifetimeTxt] = "Trips of a Lifetime!"
    txtTeam.ForeColor = vbOrange
    txtTeam.FontSize = 14
    txtTeam.FontBold = True

Else
    txtTeam.Visible = False
    txtTeam.ForeColor = 0

End If

A: Depending on what you have in your fields you probably need to add the space, as well as use ampersands:
If ([GuestFirstName] & " " & [GuestLastName] = "Angela Cockrill") Then


text:
Q: Computed Column is not allowed to be used in another computed-column definition I get Computed Column is not allowed to be used in another computed-column
 definition error message when i tried to use a computed field in another computed field. is there any workaround to accomplish this?
Computed field1
ALTER TABLE DBO.[ASSy] ADD [CALC STOCK NO] AS (

CASE
WHEN isnull([DIRECTIONAL TREAD],'') ='YES RIGHT' THEN isnull([STOCK NO],'')+'R'
WHEN isnull([DIRECTIONAL TREAD],'') ='YES LEFT' THEN isnull([STOCK NO],'')+'L'
ELSE isnull([STOCK NO],'')
end
)

Below is the second computed field. when i execute the script i get

Msg 1759, Level 16, State 0, Line 5 Computed column 'CALC STOCK NO' in
  table 'ASSy' is not allowed to be used in another
  computed-column definition.

ALTER TABLE dbo.[ASSy] ADD [PN & DESCRIPTION] AS (ISNULL([CALC STOCK NO],'')+ ', '+ISNULL([TIRE SIZE],'')+', '+ ISNULL([BH SPEC],''))

A: As per Computed Columns documentation:

A computed column is computed from an expression that can use other
  columns in the same table. The expression can be a noncomputed column
  name, constant, function, and any combination of these connected by
  one or more operators. The expression cannot be a subquery.

A computed column cannot reference another computed column. You have these options:

*

*Create a second computed column that includes the same logic as the first computed column (which cannot be referenced).

*Replace the first computed column with an ordinary column:

ALTER TABLE DBO.[ASSy] DROP COLUMN [CALC STOCK NO]
ALTER TABLE ADD [CALC STOCK NO] VARCHAR(100) NULL
UPDATE TABLE t
    SET [CALC STOCK NO] =
        CASE
        WHEN isnull([DIRECTIONAL TREAD],'') ='YES RIGHT' THEN isnull([STOCK NO],'')+'R'
        WHEN isnull([DIRECTIONAL TREAD],'') ='YES LEFT' THEN isnull([STOCK NO],'')+'L'
        ELSE isnull([STOCK NO],'')
        END
FROM [CALC STOCK NO] t

*Create a VIEW on top of the table and implement your second column in it:

CREATE VIEW DBO.[vASSy]
AS
SELECT   t.*
        ,[PN & DESCRIPTION] = (ISNULL([CALC STOCK NO],'')+ ', '+ISNULL([TIRE SIZE],'')+', '+ ISNULL([BH SPEC],''))
FROM DBO.[ASSy] t

A: Not allowed.
Workarounds are to repeat the entire code in the other column's definition or encapsulate the shared code in a scalar UDF or pull the logic up to a view (which is typically sufficient if it's not a persisted column for indexing purposes)


text:
Q: How can I round off all the rating, but ignore it if it is null or empty in laravel? How can I round off all rating but ignore it if its null or 0?
Below is my code:
$star = $ratings->count() > 0 ?
    round($ratings->sum('rating') / $ratings->count(), 2) :
    'No rating yet';

A: Try this:
$star = count($ratings) > 0 ? round($ratings->sum('rating') / $ratings->count(), 2) :'No rating yet';

or:
public $star='No rating yet';
if($ratings){
    $star = count($ratings) > 0 ? round($ratings->sum('rating') / $ratings->count(), 2) :'No rating yet';
}

A: You can achieve this using the following code
$star = $ratings->count() > 0 ? (empty($ratings->sum('rating'))?$ratings->sum('rating'): round($ratings->sum('rating') / $ratings->count(), 2)) : 'No rating yet';

I would recommend if you go this  checking in Eloquent Using below code
$model = Model::avg('rating');
$star = is_null($model->rating)?'No rating yet': round($model->rating,2);

The above will be memory-optimized. As the way you were doing it will bring all the records from the Database and Load in the memory. If you only want to show average getting only Average from the Database is more memory optimized and will improve performance later on


text:
Q: JMeter IF-condition check In client-side script 1st user creates events in a calendar for 2nd user, 2nd user accepts/declines them.
I would like to exclude possible errors during event creation and check if event request was created before 2nd user tries to accept it using xpath built on event request template like:
EventRequest_SubjectN
(N is iteration number of event request in a cycle, so if event request N wasn't created by 1st user, 2nd user action with event N fails).
Between these actions are another actions of both users, by this reason I can't use ${JMeterThread.last_sample_ok}.
Is there any analog of this function, but for necessary/specific action several steps ago, not for last sample?
What is the best way to organize IF-condition is that case?
I think about to add BeanShell PostProcessor after 1st user Event request N with a code like:
var rc = prev.getResponseCode();
if(rc.equals("200")){
vars.put('EventRequest_Subject_${N}', 'EventRequest_Subject_${N}');
}
and use not null condition for EventRequest_Subject_${N} in IF-controller for 2nd user.
But it doesn't work in this way. Where am I wrong?
UPD. Solution:
Tried 3 ways:

*

*if Event_RequestN created - put into variable specific value, then use it in IF-condition before 2nd user action with Event_RequestN;

*add action with specific assertion before 2nd user action with Event_RequestN and use ${JMeterThread.last_sample_ok} in IF-condition;

*add action with xpath extractor before 2nd user action with Event_RequestN and use ${_isVarDefined(EventRequest_Subject${N}_FOUND)} in IF-condition;
and ended up with 3rd variant as the best on practice.

A: *

*Don't use Beanshell, since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting

*Don't inline JMeter Functions or Variables into scripts, go for code-based equivalents instead

*As per JMeter Documentation

Properties are not the same as variables. Variables are local to a thread; properties are common to all threads

so if you want to share a piece of data between 2 threads (virtual users) you need to use props, not vars

*It's easier to implement your scenario using Inter-Thread Communication Plugin


text:
Q: How to filter by timestamp using TableClient from @azure/data-tables I have an azure storage table which Im trying to filter by timestamp. I am using TableClient by @azure/data-tables to achieve this. I used odata query expression to do the filtering.
import { AzureNamedKeyCredential, TableClient } from "@azure/data-tables";

 const credential = new AzureNamedKeyCredential("AccountName", "AccountKey");
 const tableName = "SomeTable";

 const serviceClient = new TableClient(      `https://${connectionObject.AccountName}.table.core.windows.net`,
     tableName,
     credential
 );

const page = await serviceClient
    .listEntities({
         queryOptions: {
            // filter: `RowKey ge 'someunixvalue'`, //this works
            filter: `timestamp ge datetime'2022-06-27T02:57:35.1831423Z'` //this doesnt work.
         }
     })
   .byPage({ maxPageSize: 1000, continuationToken })
   .next();

I have confirmed that the data has a field called timestamp and the value is 2022-06-27T02:57:35.1831423Z for one of the entities. The value of page.value will be an empty array for the failed case whereas the passing case has values.
What am I missing?


text:
Q: ASP.Net Server.Transfer and Hiddenfield I try to save on Onclientclick to my hiddenfield a string value but it doesnt work I think because of Server.Transfer();
In my is only one control for postback(Dropdownlist) if I change dropdown value I get work Server.Transfer at last in my code.
Here is the code :
$(document).ready(function () {

    alert($("[id*=hdnSelectedDiv]").val());
});

function SaveDiv(value) {
    $("[id*=hdnSelectedDiv]").val(value);
}

   <asp:LinkButton runat="server" CssClass="card-link" ID="lnkGoToLogin" OnClientClick="SaveDiv('dvLogin');return false;" meta:resourcekey="lnkGoToLoginRes"></asp:LinkButton></p>

Here is my OnSelectedIndexChanged :
   CurrentSession.SetCurrentLanguage(ddl.SelectedValue);
        ddl.SelectedValue = CurrentSession.CurrentLanguage.IetfLanguageTag;
        Thread.CurrentThread.CurrentCulture = new CultureInfo(ddl.SelectedValue);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddl.SelectedValue);
        Server.Transfer(Request.Url.AbsolutePath);

On document ready alert is my value always empty.I try to set value on my document and alert the value it is working.but if I click linkbutton and select any option in my dropdown after postback is my value empty.
How can I solve this I dont want to use Response.Redirect();

A: That hidden field must have name property.
When the postback occurs, within the server code, is the moment when you can retrieve posted values. This is the time to process them - because, after Server.Transfer starts executing, source context is gone. If you need those values within the target request (the handler transferred to), you need to pass them to it. Your options are: persisted storage (e.g. database), session (might be the best in your case), query.


text:
Q: FileNotFoundException: Automapper.Net4 in Silverlight 5 with Automapper 3.1.0 I have strange issue in one of my machine with project on Silverlight 5 with Automapper 3.1.0 where I get following error:
System.IO.FileNotFoundException occurred
Message=Could not load file or assembly 'AutoMapper.Net4, Version=3.1.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005' or one of its dependencies.
The system cannot find the file specified.
I have tried all options but not able to find out why I get this error in the project.

A: Quoting Jimmy Bogard on this issue:

It just tried to load anything it can find - because I can't detect the runtime, I can't know the exact right assembly, so I just go off a hard-coded, well-known list ( https://github.com/AutoMapper/AutoMapper/blob/f969b94444e6e3c1c71a3582cc6132044b983ed6/src/AutoMapper/Internal/PlatformAdapter.cs#L7). I then just use NuGet's multi-platform capabilities to make sure your project only references the platform-specific assemblies, even though in the package I have all platforms inside.

Basically this means that right now you can either disable "Break on all exceptions" or hit F5, since this won't be a problem (the exception is caught internally).


text:
Q: How do i unit test a class that uses IoC container classes I am using Autofac in my project,but i am unable to do a unit test on one particular class.
Consider the following Scenario :
//Class to be tested
public Class A
{
  private SomeAutoFacClass B;

  public void DoSomething()
  {
    B = scope.Resolve<ClassName>();// Resolve the object needed
    // Do something with instance B
  }
}

// Test class
public Class ATest
{
  private A a;

  [test]
  public void TestMethod()
  {
    a.DoSomething();//*This method causes a null reference exception as it tries to resolve the objects*
  }
}

In the code above,i am not able to unit test case due to the dependency injection which is only specific to that particular class.
how do i solve this? I also tried creating a autofaccontainer using Moq.
But that too fails.

A: The reason you are not able to test your class is because your class takes a dependency on your DI Container. This is an implementation of the Service Locator anti-pattern. It's an anti-pattern because:

the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

Instead, design your classes around

*

*Constructor Injection in case the class is a component (a class that contains the applications behavior), where you inject the dependencies that a class directly needs through the constructor

*Method Injection when the class is a data-centric object like an entity, which means the dependency is supplied to a the public method of such class, where the consuming class only uses that dependency, but not stores it.

Components are built-up by your DI Container and are registered in your Composition Root, while data-centric objects are newed up in code outside the Composition Root. In that case you need to pass along a dependency to an already constructed object.
In case you build and test a component, your code would typically look as follows:
public class ComponentA
{
    private ClassName b;

    public ComponentA(ClassName b)
    {
        this.b = b;
    }

    public void DoSomething()
    {
        // Do something with instance B
    }
}

// Test class
public Class ATest
{
    [test]
    public void TestMethod()
    {
        // Arrange
        B b = new FakeB();

        var a = new ComponentA(b);

        // Act
        a.DoSomething();

        // Assert
        // Check whether be was invoked correctly.
    }
}

In case you build and test a data-centric object that requires a dependency for one of its operations, your code would typically look as follows:
public class EntityA
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void DoSomething(ClassName b)
    {
        // Do something with instance B
    }
}

// Test class
public Class ATest
{
    [test]
    public void TestMethod()
    {
        // Arrange
        B b = new FakeB();

        var a = new EntityA { Name = "Bert", Age = 56 };

        // Act
        a.DoSomething(b);

        // Assert
        // Check whether be was invoked correctly.
    }
}

So to answer your initial question:

How do i unit test a class that uses IoC container classes

You don't. Your application code should not depend on the DI Container, because that leads to all kinds of complications such as being hard to test.

A: Using an IoC container you should aim to use IoC. Normally this is either constructor injection or property injection depending on what your container can support for auto-injection.
A pattern I use for this I call "lazy property injection" where I constructor-inject my container to act as a registry, then use the lazy resolution on property use..
What it looks like:
private readonly IoCContainer _container = null;

private IMyService _myService = null;
public IMyService MyService
{
   get { return _myService ?? (_myService = _container.Resolve<IMyService>()); }
   set { _myService = value; }
}

public MyClass( IoCContainer container)
{
   if (container == null)
      throw new ArgumentNullException("container");

   _container = container;
}

Now when you go to test a method of this class, your test initializes your MyService with a Mock.  When running under test, I have the IoCContainer initialized to a Mock() that throws if any .Resolve<> calls are made. This catches scenarios where your code under test might be modified to use a new dependency that hasn't been mocked out.
The benefit of this approach is that often a class will have several single-purpose methods, and by extension need a number of dependencies. In applications like web requests where maybe only one method is called, needing one dependency, the dependency resolution only retrieves the dependencies from the container that are needed, not all of them. (I.e. if you use constructor injection with 8 dependencies, all 8 need to be resolved at runtime, even if only 1 will be used.) This also simplifies unit testing to only mock out what you know will be needed rather than everything.


text:
Q: How to fix NoNode error - storm kafka? I am working on storm and kafka. I am using this project.
Note
I am running this project locally. It is throwing following error.
java.lang.RuntimeException: java.lang.RuntimeException: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /brokers/topics/clickstreamlog/partitions
at storm.kafka.DynamicBrokersReader.getBrokerInfo(DynamicBrokersReader.java:81) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
at storm.kafka.trident.ZkBrokerReader.<init>(ZkBrokerReader.java:42) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
at storm.kafka.KafkaUtils.makeBrokerReader(KafkaUtils.java:57) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
at storm.kafka.KafkaSpout.open(KafkaSpout.java:87) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
at backtype.storm.daemon.executor$fn__3284$fn__3299.invoke(executor.clj:520) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
at backtype.storm.util$async_loop$fn__452.invoke(util.clj:429) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
at clojure.lang.AFn.run(AFn.java:24) [clojure-1.5.1.jar:na]
at java.lang.Thread.run(Thread.java:679) [na:1.6.0_27]
Caused by: java.lang.RuntimeException: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /brokers/topics/clickstreamlog/partitions
at storm.kafka.DynamicBrokersReader.getNumPartitions(DynamicBrokersReader.java:94) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
at storm.kafka.DynamicBrokersReader.getBrokerInfo(DynamicBrokersReader.java:65) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
... 7 common frames omitted
Caused by: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /brokers/topics/clickstreamlog/partitions
at org.apache.zookeeper.KeeperException.create(KeeperException.java:111) ~[zookeeper-3.4.5.jar:3.4.5-1392090]
at org.apache.zookeeper.KeeperException.create(KeeperException.java:51) ~[zookeeper-3.4.5.jar:3.4.5-1392090]
at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:1586) ~[zookeeper-3.4.5.jar:3.4.5-1392090]
at org.apache.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:214) ~[curator-framework-2.4.0.jar:na]
at org.apache.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:203) ~[curator-framework-2.4.0.jar:na]
at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:107) ~[curator-client-2.4.0.jar:na]
at org.apache.curator.framework.imps.GetChildrenBuilderImpl.pathInForeground(GetChildrenBuilderImpl.java:199) ~[curator-framework-2.4.0.jar:na]
at org.apache.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:191) ~[curator-framework-2.4.0.jar:na]
at org.apache.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:38) ~[curator-framework-2.4.0.jar:na]
at storm.kafka.DynamicBrokersReader.getNumPartitions(DynamicBrokersReader.java:91) ~[storm-kafka-0.9.2-incubating.jar:0.9.2-incubating]
... 8 common frames omitted

Anyone faced the same issue using storm-kafka-0.8-plus-test project.
Any suggestion will be grateful.

A: this error in current context signify, that zookeeper is not being able to automatically create any/all of following nodes -
storm-kafka, storm, zookeeper
You may try out creating the nodes manually on the zookeeper, I think that will work for u.


text:
Q: Why am I getting error FROM-clause entry for table error? I am writing an app in Rails 4.2.1 using jRuby 1.7.16.1
I've got User and Project models. Project has one leader and many users through join model:
class Project < ActiveRecord::Base
  has_many :users_projects_join
  has_many :users, :through => :users_projects_join
  has_many :active_users,
     -> { where(users_projects_join: {user_status: true}) },
     :through => :users_projects_join,
     :source => :user

  belongs_to :leader, :class_name => 'User', :foreign_key => :leader_id
end

I wanted to have :active_users so I wrote the query showed above but it gives me
ERROR: missing FROM-clause entry for table "users_projects_join"
  Position: 167: SELECT "users".* FROM "users"
    INNER JOIN "users_projects_joins"
    ON "users"."id" = "users_projects_joins"."user_id"
    WHERE "users_projects_joins"."project_id" = 20
    AND "users_projects_join"."user_status" = 't'

But when I execute this query strictly in the Postgres it gives me all users with user_status true. I read that I need to add joins(:users_projects_join).where(...) but it didn't help.

A: Try now :
class Project < ActiveRecord::Base
  has_many :users_projects_joins
  has_many :users, :through => :users_projects_joins
  has_many :active_users,
     -> { where(users_projects_joins: {user_status: true}) },
     :through => :users_projects_joins,
     :source => :user

  belongs_to :leader, :class_name => 'User', :foreign_key => :leader_id
end


text:
Q: Is there a way to play PVZ 2 Special Events more than once per day? PVZ 2 (Plants vs Zombies 2) has a special event every day.  Sometimes I finish it and want to play it again.  But it seems it won't let me play again.  Is there a way?
(I could also hit "Restart" before the last zombie dies, or can create another profile and finish at least Day 1 to Day 6 and also play the special event.  Other than that, are there any other ways?)

A: There is no way to, sorry. The daily events are designed to keep you checking back for new content every day. Allowing you to replay them would remove some of the 'specialness' from them.

A: Several months ago, a patch was released to where you can replay the pinata party once per day after completing it by watching an ad. This means you get double the rewards by beating it twice.

A: Don't have the game so can't test it but your best bet is to time glitch - move the clock of your device to the next day.


text:
Q: Unable to access all the events in a VB web form using Visual Studio 2017 RC When I create a Web Form a large chunk of the events for my objects are missing when I select the control.
Example: Button only has the Click event and Label has no events I can run.
When I created a Windows Form application, the events are all there. What can I do to get my events back?


text:
Q: Objective-C accessing Swift Package functions Goal: To use Swift Package within Objective-C.

All I'm trying to do is to have a simple, rudimentary understanding of the correct syntax of access Swift vars & func() from ObjC.
This is the second part of questions about using Objective-C with a Swift package.

Here's my Swift Package file that I'm trying to access...
I'm concentrating on the Swift class access.
But I would also like to know how to access the struct.
import Foundation

public struct RicStruct {
    public private(set) var text = "Hello, World!"

    public init() {
    }

    public func sayHello() -> String {
        "Hello Ric!"
    }
}

public class RicClass: NSObject {
    @objc public var msg = "Mother has a feeling, I might be too appealing."
    @objc public let text = "Hello Everybody!"

    public override init() {}

    public func sayHello() {
            print(text)
        }

    public func doSomething() {
        print("Inside doSomething()")
    }
}

This is the Objective-C parent attempting to access the Swift-Package vars & func:

Question: What's the proper syntax of accessing:

*

*the Swift class & struct functions,

*the Swift var/let?

A: You declared
public func sayHello() {
    print(text)
}

That makes the method sayHello public across module, but it does not expose it to Objective-C. Instead:
@objc public func sayHello() {
    print(text)
}

A: I didn't add the '@objc' qualifier to the Swift function.  I had mistakenly thought that it's not necessary due to being a member of a NSObject class per class declaration.
Also, didn't need to add the .h ObjC <--> Swift bridge file.


text:
Q: Probability for 3 balls of different colours I got this question in an exam a while ago and I wasn't sure how exactly I could solve it:
An urn contains 3 red balls, 3 blue balls and 3 green balls. Three are drawn at
random from the urn. What's the probability they're all of a different colour?

It is not specified if with or without replacement. Could someone please clarify me on both variants? Thanks :)

A: If without replacement, 1st ball could be any, 2nd could be any of 6 of the 8, 3rd any of 3 of the 7, so $(6/8)(3/7)=9/28$.
If with replacement, 1st could be any, 2nd any of 6 of the 9, 3rd any of 3 of the 9, so $(6/9)(3/9)=2/9$.


text:
Q: how start new tmux session with shell code? I want to fuzzy find a file and then open it in a new tmux window.
Unfortunately, the tmux session exits immediately, and returns a 0 exit code. If I echo the command and run it from terminal manually, it works fine. Similarly, if I copy the output of echo and make it it's own command, yy, I can execute that and it works fine too.
Another (bonus) problem appears to happen when using ZLE because it doesn't seem to set the terminal. While xx will return a 0 exit code (immediately), ctrl-x will return the warning 'not a terminal' from tmux.
xx () {
  P=$(zsh -c $FZF_DEFAULT_COMMAND | fzf +m)
  CMD="'cd $(dirname $P) && ${EDITOR:-vim} $(basename $P)'"
  echo tmux new-session $CMD
  tmux new-session $CMD
}

yy () {
  tmux new-session 'cd /data/repos/notes && nvim engineering_a_compiler.md'
}

# create zsh widgets
zle -N xx xx
# keybind zsh widgets
bindkey ^x xx

Tried following stuff in other stack overflow post here

A: For anyone who is interested, here are the relevant parts of my .zshrc_fzf configuration; the tl;dr is I don't use widgets and instead call functions directly with text bindkeys, since it seems that ZLE doesn't pass the tty on to functions executed in widgets.
This file maps ctrl+p to fuzzy find a file using fd, change to the containing directory, and open it in an editor. If you're not in a tmux session, it does the same after opening a tmux session (in addition to changing to the project directory before starting the tmux session so it's the root of all future tmux-panes in that session).
It does the same thing with ctrl+f, but uses ripgrep (rg) to search for a file by file contents instead.
not defined in this file: source_if_exists() { if [ -f $1 ]; then source $1; fi }
#!/usr/bin/zsh
# SOURCE: https://github.com/junegunn/fzf/wiki/examples
source_if_exists /usr/share/fzf/key-bindings.zsh
source_if_exists /usr/share/fzf/completion.zsh

FZF_PREVIEW="'head -100 {}'"
FZF_VIM_PLUGIN_PREVIEW=~/.local/share/nvim/plugged/fzf.vim/bin/preview.sh
if [[ -f $FZF_VIM_PLUGIN_PREVIEW ]]; then
  FZF_PREVIEW=$FZF_VIM_PLUGIN_PREVIEW
fi
FZF_DEFAULT_OPTS="--layout=reverse --height='40%' --preview='"$FZF_PREVIEW" {}'"
export FZF_RIPGREP_OPTS="--column --line-number --no-heading --hidden --ignore-file $HOME/.gitignore_global"
export FZF_DEFAULT_COMMAND="fd . $SEARCH_DIRS --hidden --ignore-file ~/.gitignore_global"
FZF_CTRL_T_COMMAND=$FZF_DEFAULT_COMMAND

edit () {
  P=$1
  # file
  if [[ -f $P ]]; then
    if [[ $TERM != tmux* ]]; then  # not in tmux session
      # change to project directory, becomes root of new tmux-panes
      cd $(dirname $P)
      if [[ $(git rev-parse --is-inside-work-tree 2>/dev/null) == "true" ]]; then
        cd $(git rev-parse --show-toplevel)
      fi
      tmux new-session "cd $(dirname $P) && ${EDITOR:-vim} $(basename $P); zsh"
      clear
    else  # within existing tmux session
      cd $(dirname $P) && ${EDITOR:-vim} $(basename $P)
    fi
  # directory
  elif [[ -d $P ]]; then
    cd $P
  fi
}

# find path, change to directory, if path is a file, open in $EDITOR
fd_find () {
  edit $(zsh -c $FZF_DEFAULT_COMMAND | fzf +m)
}

rg_find () {
  CMD="rg $FZF_RIPGREP_OPTS ${1:-'.*'} $SEARCH_DIRS"
  edit $(zsh -c $CMD | fzf +m | cut -d: -f1)
}

# zsh shortcuts
bindkey -s ^p 'fd_find\n'
bindkey -s ^f 'rg_find\n'

A: The problem is with how you are defining CMD. The hard-coded tmux command would be (using the -c option to simplify things)
tmux new-session -c "$(dirname "$P")" "${EDITOR:-vim} "$(basename "$P")"

To make store the command and its arguments, use an array.
xx () {
  P=$(zsh -c "$FZF_DEFAULT_COMMAND" | fzf +m)
  CMD=("${EDITOR:-vim}" "$(basename "$P")")
  echo "tmux new-session ${CMD[*]}"
  tmux new-session -c "$(dirname "$P")" "${CMD[@]}"
}


text:
Q: Where does bash prompt escape sequence \h get the hostname from? \h is a bash prompt escape sequence that expands to the hostname. Where does it get the hostname from? On my system it shows a value that I cannot find anywhere, not in hostname -f or /etc/hosts or /etc/hostname or /etc/sysconfig/network or $HOSTNAME. So I'm wondering where it's getting it from. My system is Centos 7.4. I know there are hidden places where things such as UUIDs are stored, and I seem to recall that I've come across a similar hidden hostname type of issue in the past, but I can't remember the details.

A: If you look at the bash source code you'll see in shell.c that it calls gethostname(2), a POSIX system call that retrieves the hostname from the kernel.
/* It's highly unlikely that this will change. */
if (current_host_name == 0)
  {
    /* Initialize current_host_name. */
    if (gethostname (hostname, 255) < 0)
      current_host_name = "??host??";
    else
      current_host_name = savestring (hostname);
  }

This is not necessarily a canonical string. The kernel doesn't actually know the machine's network hostname. It just reports back whatever was passed to sethostname(2). To quote from the uname(2) man page:

On the other hand, the [hostname] is meaningless: it gives the name of the present machine in some undefined network, but typically machines are in more than one network and have several names.  Moreover, the kernel  has  no  way  of  knowing  about  such things, so it has to be told what to answer here.

On non-Linux systems without gethostname(2), bash falls back to uname(2). If uname(2) isn't even available then it simply displays "unknown". You can see that logic in lib/sh/oslib.c:
#if !defined (HAVE_GETHOSTNAME)
#  if defined (HAVE_UNAME)
#    include <sys/utsname.h>
int
gethostname (name, namelen)
     char *name;
     int namelen;
{
  int i;
  struct utsname ut;

  --namelen;

  uname (&ut);
  i = strlen (ut.nodename) + 1;
  strncpy (name, ut.nodename, i < namelen ? i : namelen);
  name[namelen] = '\0';
  return (0);
}
#  else /* !HAVE_UNAME */
int
gethostname (name, namelen)
     char *name;
     int namelen;
{
  strncpy (name, "unknown", namelen);
  name[namelen] = '\0';
  return 0;
}
#  endif /* !HAVE_UNAME */
#endif /* !HAVE_GETHOSTNAME */

\h isn't updated if the hostname changes. The value is cached at startup when the shell is initialized.
[jkugelman@malkovich]$ hostname
malkovich
[jkugelman@malkovich]$ sudo hostname kaufman
[jkugelman@malkovich]$ hostname
kaufman
[jkugelman@malkovich]$ bash
[jkugelman@kaufman]

A: It probably (just a guess) uses the gethostname(2) system call (which is handled by the kernel, as all syscalls(2) are...)
BTW, GNU bash is (as most packages of your Linux distributions are) free software; so please download its source code and study it; use the source, Luke! and open the source more, please.
A more interesting question is how that information is cached by bash. Does it call gethostname at every command? You might also use strace(1) to find out.

Of course, take the habit of studying the source code of free software every time you are curious. And use strace -and the gdb debugger- to understand their dynamic behavior.
A French singer, G.Bedos, told us "La liberté ne s'use que si on ne s'en sert pas", that is

Freedom wears out if you don't use it.

(translation is mine, I am French but not a native English speaker)

So next time, please dive into the source code of free software. It is important to exercise your freedom, and that is what free software is about.


text:
Q: How to add Rails-Jquery back to Rails app? I'm working with ROR 4.  I posted this question about how my link_to wouldn't POST correctly using { method: :post }.
I figured out this was because I removed the Rails-Jquery gem when I first set up my app (this is a side project, I hadn't planned on using Javascript/jQuery or so I thought!).
In an effort to get my POST working, I added the gem back to Gemfile.  The file now looks like this:
    source 'https://rubygems.org'

    gem 'aws-sdk'
    gem 'faker'
    gem 'jquery-rails'
    gem 'inline_svg'
    gem 'jbuilder', '~> 2.0'
    gem 'nokogiri'
    gem 'paperclip'
    gem 'pg'
    gem 'rails', '~> 4.2.0'
    gem 'sass-rails'

I did a bundle install.
I added the below code to application.js:
    //= require jquery
    //= require jquery_ujs
    //= require_tree .

What am I missing?  jQuery still isn't loading in the Network tab in Chrome.
I'm guessing I must have changed another config setting on setup (5 weeks ago) that I am now forgetting.
UPDATE:  I also removed turbolinks during the main setup.  Is that needed for jQuery to work?

A: If you removed javascript during the initial setup, you are probably missing this from the head of your application.html.erb layout.
<%= javascript_include_tag 'application' %>


text:
Q: How to Bulk Update post titles wordpress through mySQL All my post titles have a static word in front of them. I have over 9000 published posts with two different static words in my post titles. I am trying to remove this word from all my posts.
Essentially, I am looking for a way to remove that constant word. I tried using export through wordpress and editing the post titles that way, but the file was 100mb + and simply won't open.
I looked towards SQL/phpmyadmin but I am not very well versed with SQL queries and don't want to mess up my database.

The "Constant" is always the first word of the title. What could I do
  to instead have mysql detect the first space and remove everything
  before it as well as including the space. Essentially, removing the
  first word. Basically I have more than one constant, so it would be
  better if I could just find the first space in the string and then
  remove it and everything before it. I'm assuming we'd use sub_string
  or something.

This is the title structure

Constant other stuff here

so if there is a search query where it finds "Constant " and a space and replaces it with "" nothing, that way I could have it completely removed. It'd be great if it could be a search and replace query, so I could utilize it later.
Information on the Database / Table / Column
the table is called: wp_posts and it needs to be restricted to the value of the table post_type when it's value is post and the title is in the post_title column
Any help would be greatly appreciated.

A: MySQL doesn't have exactly what you're looking for -- yes, there is a REPLACE() string function, but you can't limit it to a single substitution.  As such, you might inadvertently replace other occurrences of this constant that could conceivably appear in your title string.
IMHO, the easiest way is to find all titles starting with your constant, and just replace the first one (i.e. at the start of the string):
UPDATE wp_posts
SET post_title =
MID( post_title, LENGTH('Constant ')+1 )
WHERE post_title LIKE 'Constant %'
AND post_type = 'post';

You need the +1 because MySQL string offsets start at 1, not zero.
Personally, I always prefer to run the equivalent SELECT first, just to be certain (too many years of MyISAM without BEGIN WORK):
SELECT post_title,
MID( post_title, LENGTH('Constant ')+1 ) AS replacedTitle
FROM wp_posts
WHERE post_title LIKE 'Constant %'
AND post_type = 'post';

Alternatively, if you're certain that you always want to remove the first word (i.e. up to and including the first space), then the following statement should work:
UPDATE wp_posts
SET post_title =
MID( post_title, POSITION( ' ' IN post_title )+1 )
WHERE post_type = 'post';

Since POSITION() will return zero if no space is found, this statement will be a no-op (i.e. non-destructive) in the general case.

A: Search RegEx is a great plugin to be able to search and replace - with grep or plain text - through all post and page content, post titles, post meta, etc. Does not search custom post types.
Back up your DB before making any changes, either with this plugin or direct query in the database.
Docs: http://urbangiraffe.com/plugins/search-regex/


text:
Q: javascript setting absolute position for ipad when the page loads the first time Absolute positioning is working after the iPad's orientation is changed. When the page first loads there is no positioning.
How do I get the page to load with the correct position to the correct orientation?

A: Two steps to this:

*

*Move your scripts (all of them) to the bottom of the HTML, just before the closing  tag. That way, downloading your scripts doesn't hold up rendering your page; and (more relevant to your question) the elements they try to act on will exist before they run. More: YUI Best Practices for Speeding Up your Website

*Add a call to your function:
detectIPadOrientation();

Side note: No need for the type attribute, JavaScript is the default.
So (see comments):


text:
Q: Specifying Absolute Path using VBScript I have VBScript that is taking output from a Word file and generating a text file with that output. The current code shown below assumes that I want to create the file in my desktop.
The issue that I am having is that I plan to use wine on Linux to execute my VBScript. Is there anyway that i can modify this code to specify the Linux path to output this file?
fileName = "\out.txt"
strPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & fileName

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile(strPath)