text:
Q: Like query in ElasticSearch How to use a like query in a elasticsearch query?
this is what i have been trying so far.
array:3 [
"index" => "users"
"type" => "user"
"body" => array:1 [
"query" => array:1 [
  "bool" => array:1 [
    "should" => array:1 [
      0 => array:3 [
        0 => array:1 [
          "match" => array:1 [
            "fullname" => "Mag*"
          ]
        ]
        1 => array:1 [
          "match" => array:1 [
            "industry_name" => "other"
          ]
        ]
        2 => array:1 [
          "match" => array:1 [
            "active" => "yes"
           ]
         ]
       ]
     ]
     ]
     ]
   ]
   ]

My Search json is something like this,
{"1": "Mag","industry_name":"other", "active": "yes"}

In my indexes, there is a record for the full name "Maggie Wilfred".
when i run this query nothing gets returned.
any reason?.i feel the problem is in the wild card? "fullname" => "Mag*"

A: It should work, try it in this way:
    {
        "wildcard" : { "fullname" : "Mag*" }
    }

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html

A: The match query doesn't support wildcards as stated on https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
You should try with the Wildcardquery.

A: {
    "prefix" : { "fullname" : "Mag" }
}


text:
Q: Function that counts numbers with multiple digits in Haskell I'm trying to write a function that counts all numbers from a String in Haskell that have more than 1 digit.
Example 1: "Test1 Test12"
This should return 1 because only "Test12" has more than 1 digit.
Example 2: "Test1 Test12 Test123"
This should return 2 because only "Test12" and "Test123" have more than 1 digit.
This is how my code currently looks like:
import Data.Char
import Data.List
import Data.Function

digits = any ((1<) . length) . groupBy ((&&) `on` isDigit)

count :: String -> Int
count n = length (filter digits n)

Can anyone help me here?

A: Your problem can be broken down into

*

*I want to count the number of words in a string that have more than one digit

*I want to find the words in a string that have more than one digit

*I want to determine if a word has more than one digit

*I want to count the number of digits in a word

So the most basic thing that you want to do is count the number of digits in a word.  Since a word is a string, that can be easily done by
count :: String -> Int
count word = length $ filter isDigit n

Then you want to determine if a word has more than one digit, which means it should return a Bool:
hasManyDigits :: String -> Bool
hasManyDigits word = count word > 1

Then you want to find the number of words in a sentence with many digits:
wordsWithManyDigits :: String -> [String]
wordsWithManyDigits sentence = filter hasManyDigits $ words sentence

Then you want to count them
countWordsWithManyDigits :: String -> Int
countWordsWithManyDigits sentence = length $ wordsWithManyDigits sentence

The words function splits a string on spaces, and the Data.Char.isDigit function I think is pretty self-explanatory.

You could could combine these into a single function as
count :: String -> Int
count = length . filter ((> 1) . length . filter isDigit) . words

But I think that makes it lose its readability, even though it displays Haskell's ability to compose functions quite well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why my ItemListener doesn't work? I'm trying to implements ItemListener in JCheckBox.
The following code works:
public class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel p = new JPanel();
        p.setLayout(new FlowLayout());

        int size = 5;
        JLabel[] labels = new JLabel[size];
        for (int i = 1; i < labels.length; i++) {
            labels[i] = new JLabel();
            labels[i].setText("" + i);
            ;

            labels[i].setPreferredSize(new Dimension(25, 25));
            p.add(labels[i]);
        }

        JCheckBox[] checkBoxs = new JCheckBox[size];
        for (int i = 1; i < checkBoxs.length; i++) {
            checkBoxs[i] = new JCheckBox();
            checkBoxs[i].setSelected(true);
            p.add(checkBoxs[i]);
            checkBoxs[i].addItemListener(new MyItemListener(labels[i]));
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setContentPane(p);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

and the listener class:
public class MyItemListener implements ItemListener {

JLabel label = new JLabel();

public MyItemListener(JLabel label) {
    super();
    this.label = label;
}

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
        label.setVisible(true);
        label.revalidate();
        label.repaint();
    } else {
        label.setVisible(false);
    }
}

}
But now, I'm trying to do the same things with separate class, but it doesn't work:
Test.java
public class Test {
public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout());

    PanelOfLabel panelOfLabel = new PanelOfLabel();
    panelOfLabel.setBorder(new LineBorder(Color.red));
    p.add(panelOfLabel);

    PanelOfBoxes panelOfBoxes = new PanelOfBoxes();
    panelOfBoxes.setBorder(new LineBorder(Color.green));
    p.add(panelOfBoxes);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setContentPane(p);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

}
PanelOfLabel.java
public class PanelOfLabel extends JPanel {

private JLabel[] labels = new JLabel[5];

public PanelOfLabel() {
    super();
    createLabels();
}

public void createLabels() {
    for (int i = 1; i < labels.length; i++) {
        labels[i] = new JLabel();
        labels[i].setText("" + i);
        labels[i].setPreferredSize(new Dimension(25, 25));
        this.add(labels[i]);
    }

}

PanelOfBoxes.java
public class PanelOfBoxes extends JPanel {

private JCheckBox[] checkBoxs = new JCheckBox[5];
private PanelOfLabel[] PanelOfLabels = new PanelOfLabel[5];

public PanelOfBoxes() {
    super();
    createBoxes();
}

public void createBoxes() {
    for (int i = 1; i < checkBoxs.length; i++) {
        checkBoxs[i] = new JCheckBox();
        checkBoxs[i].setSelected(true);
        this.add(checkBoxs[i]);
        checkBoxs[i].addItemListener(new MyListener(PanelOfLabels[i]));
    }
}

}
and MyListener.java
public class MyListener implements ItemListener {

private PanelOfLabel panelOfLabels;

public MyListener(PanelOfLabel panelOfLabels) {
    super();
    this.panelOfLabels = panelOfLabels;
}

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
        panelOfLabels.setVisible(true);
        panelOfLabels.revalidate();
        panelOfLabels.repaint();
    } else {
        panelOfLabels.setVisible(false);
    }
}

}
Where is the mistake that i made ? Can somebody help me please ?

A: This doesn't make sense:
private PanelOfLabel[] PanelOfLabels = new PanelOfLabel[5];

public PanelOfBoxes() {
    super();
    createBoxes();
}

public void createBoxes() {
    for (int i = 1; i < checkBoxs.length; i++) {
        checkBoxs[i] = new JCheckBox();
        checkBoxs[i].setSelected(true);
        this.add(checkBoxs[i]);
        checkBoxs[i].addItemListener(new MyListener(PanelOfLabels[i]));
    }
}

Since each PanelOfLabels item has not been constructed, each item will be null. You're passing a null reference into your MyListener constructor.
And shouldn't you instead be passing in one JLabel into that constructor and not an array of JPanel?
e.g.,
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.LineBorder;

public class Test {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());

      PanelOfLabel panelOfLabel = new PanelOfLabel();
      panelOfLabel.setBorder(new LineBorder(Color.red));
      p.add(panelOfLabel);

      PanelOfBoxes panelOfBoxes = new PanelOfBoxes(panelOfLabel); //!!
      panelOfBoxes.setBorder(new LineBorder(Color.green));
      p.add(panelOfBoxes);

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400, 400);
      frame.setContentPane(p);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}

class PanelOfLabel extends JPanel {
   private JLabel[] labels = new JLabel[5];

   public PanelOfLabel() {
      super();
      createLabels();
   }

   public void setLabelVisibility(int index, boolean visible) {
      if (index < 0 || index >= labels.length) {
         throw new ArrayIndexOutOfBoundsException(index);
      }

      labels[index].setVisible(visible);
   }

   public void createLabels() {
      for (int i = 1; i < labels.length; i++) {
         labels[i] = new JLabel();
         labels[i].setText("" + i);
         labels[i].setPreferredSize(new Dimension(25, 25));
         this.add(labels[i]);
      }

   }
}

class PanelOfBoxes extends JPanel {

   private JCheckBox[] checkBoxs = new JCheckBox[5];
   // !! private PanelOfLabel[] PanelOfLabels = new PanelOfLabel[5];
   private PanelOfLabel panelOfLabel; //!!

   public PanelOfBoxes(PanelOfLabel panelOfLabel) {
      super();
      this.panelOfLabel = panelOfLabel; //!!
      createBoxes();
   }

   public void createBoxes() {
      for (int i = 1; i < checkBoxs.length; i++) {
         checkBoxs[i] = new JCheckBox();
         checkBoxs[i].setSelected(true);
         this.add(checkBoxs[i]);
         // !!
         checkBoxs[i].addItemListener(new MyListener(i, panelOfLabel)); //!!
      }
   }
}

class MyListener implements ItemListener {

   private PanelOfLabel panelOfLabels;
   private int index;

   // !!
   public MyListener(int index, PanelOfLabel panelOfLabels) {
      super();
      this.index = index; // !!
      this.panelOfLabels = panelOfLabels;
   }

   @Override //!!
   public void itemStateChanged(ItemEvent e) {
      boolean visible = e.getStateChange() == ItemEvent.SELECTED;
      panelOfLabels.setLabelVisibility(index, visible);
      Container parent = panelOfLabels.getParent();
      parent.repaint();
   }
}

Edit
My attempt at a Model-View-Control (MVC) solution:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.IndexedPropertyChangeEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

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

public class TestMvc {

   private static final int SIZE = 6;

   private static void createAndShowGui() {
      TestModel model = new TestModel(SIZE);
      TestView view = new TestView();
      new TestControl(model, view);

      JFrame frame = new JFrame("TestMvc");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(view.getMainPanel());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

class TestControl {

   private TestModel model;
   private TestView view;

   public TestControl(final TestModel model, final TestView view) {
      this.model = model;
      this.view = view;
      view.setModel(model);
      TestViewCheckBoxBox checkBoxBox = view.getCheckBoxBox();
      for (int i = 0; i < model.getSize(); i++) {
         checkBoxBox.addCheckBoxItemListener(i, new MyItemListener(i));
      }

      model.addPropertyChangeListener(new ModelPropertyChangeListener());
   }

   private class MyItemListener implements ItemListener {
      private int index;

      public MyItemListener(int index) {
         this.index = index;
      }

      @Override
      public void itemStateChanged(ItemEvent iEvt) {
         model.setValue(index, iEvt.getStateChange() == ItemEvent.SELECTED);
      }
   }

   private class ModelPropertyChangeListener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent pcEvt) {
         if (TestModel.VALUE.equals(pcEvt.getPropertyName())) {
            IndexedPropertyChangeEvent ipcEvt = (IndexedPropertyChangeEvent) pcEvt;
            int index = ipcEvt.getIndex();
            boolean visible = (Boolean)ipcEvt.getNewValue();
            view.getLabelBox().setLabelVisible(index, visible);
         }
      }
   }

}

class TestView {
   private JPanel mainPanel = new JPanel();
   private TestModel model;
   private TestViewLabelBox labelBox;
   private TestViewCheckBoxBox checkBoxBox;

   public void setModel(TestModel model) {
      this.model = model;
      mainPanel.setLayout(new GridLayout(1, 0, 5, 0));
      labelBox = new TestViewLabelBox(model.getSize());
      checkBoxBox = new TestViewCheckBoxBox(model.getSize());

      mainPanel.add(labelBox.getMainPanel());
      mainPanel.add(checkBoxBox.getMainPanel());
   }

   public TestViewLabelBox getLabelBox() {
      return labelBox;
   }

   public TestViewCheckBoxBox getCheckBoxBox() {
      return checkBoxBox;
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

}

class TestViewLabelBox {
   private JPanel mainPanel = new JPanel();
   private List<JLabel> labelList = new ArrayList<>();

   public TestViewLabelBox(int count) {
      mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));
      mainPanel.setLayout(new GridLayout(1, 0, 5, 0));
      for (int i = 0; i < count; i++) {
         JLabel label = new JLabel(String.valueOf(i + 1), SwingConstants.CENTER);
         labelList.add(label);
         mainPanel.add(label);
      }
   }

   public void setLabelVisible(int index, boolean visible) {
      if (index < 0 || index >= labelList.size()) {
         throw new ArrayIndexOutOfBoundsException(index);
      }
      String text = visible ? String.valueOf(index + 1) : "";
      labelList.get(index).setText(text);
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

}

class TestViewCheckBoxBox {
   private JPanel mainPanel = new JPanel();
   private List<JCheckBox> checkBoxList = new ArrayList<>();

   public TestViewCheckBoxBox(int count) {
      mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));
      mainPanel.setLayout(new GridLayout(1, 0, 5, 0));
      for (int i = 0; i < count; i++) {
         JCheckBox checkBox = new JCheckBox("", true);
         checkBoxList.add(checkBox);
         mainPanel.add(checkBox);
      }
   }

   public void addCheckBoxItemListener(int index, ItemListener itemListener) {
      if (index < 0 || index >= checkBoxList.size()) {
         throw new ArrayIndexOutOfBoundsException(index);
      }
      checkBoxList.get(index).addItemListener(itemListener);
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }
}

class TestModel {
   public static final String VALUE = "value";
   private List<Boolean> values = new ArrayList<>();
   private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
         this);

   public TestModel(int size) {
      for (int i = 0; i < size; i++) {
         values.add(Boolean.TRUE);
      }
   }

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

   public int getSize() {
      return values.size();
   }

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

   public boolean getValue(int index) {
      if (index < 0 || index >= values.size()) {
         throw new ArrayIndexOutOfBoundsException(index);
      }
      return values.get(index);
   }

   public void setValue(int index, boolean value) {
      if (index < 0 || index >= values.size()) {
         throw new ArrayIndexOutOfBoundsException(index);
      }
      boolean oldValue = getValue(index);
      boolean newValue = value;
      values.set(index, value);
      pcSupport.fireIndexedPropertyChange(VALUE, index, oldValue, newValue);
   }
}

A: private PanelOfLabel[] PanelOfLabels = new PanelOfLabel[5];

Here you're creating an array of PanelOfLabel, containing null elements.
checkBoxs[i].addItemListener(new MyListener(PanelOfLabels[i]));

and here you add a listener to your checkboxes, and pass one of the null elements to the listener.
First decide what you want to make visible/invisible in your ItemListener. Is it one of your JLabels, or is it the only PanelOfLabel instance created in the main class? My guess is that it's the labels. So the listener should be identical to the one you have in your working example. But you have to make sure that the labels passed to the listener are the ones created and added in PanelOfLabel.
Side note: you're confusing yourself, and us, by not respecting the Java naming conventions. Variables start with a lowercase letter.


text:
Q: Carrierwave for image upload with ruby on rails I am trying to upload image using carrierwave. Everything seems to be correct, but I am repeatedly getting an error stating:
Can't resolve image into URL: undefined method `to_model' for #<PortfolioUploader:0x007f35a5cad3c0>
Did you mean?  to_xml

A: CarrierWave with Rails 5.2 ActiveStorage may have some issues.
You could try to change your classic image_tag.
Assuming you're using something like this :
<%= image_tag(@user.image) %>

Change it to something like this, using .url
<%= image_tag(@user.image.url) %>


text:
Q: convert an application iPad in a iPhone (how to make...the popover) I have an iPad application that opens a box by pressing a button that works as a popover. would be possible to convert it into a iphone application where when I press the button opens a full screen view specific?

A: Based on comments you should checkout following tutorial:
http://www.roseindia.net/tutorial/iphone/examples/iphone-imagebuttonchangeview.html
Kind regards,
Bo


text:
Q: How do make a field be debug-only in C#? I'm having trouble the same instance of a C# class being used in multiple places.  I'd like to be able to tell at a glance in the debugger which instance is which, so I've added a field called DebugUID like so:
public readonly string DebugUID = Guid.NewGuid().ToString();

and I've also added the attribute [DebuggerDisplay("DebugUID= {DebugUID}")] to the class.
I'd like the compiler to ignore the DebugUID field in release mode.  If it were a method, I'd add [Conditional("Debug")] before it, but it won't let me do that for fields.  How do make a field be debug-only in C#?

A: Can I suggest an alternative that involves using the debugger rather than writing code?
Right-click the instance in the watch window and choose "Assign Object ID". That object will now appear with that ID throughout your debug session. Repeat for other instances of the same class that are of interest to you.

A: C# has conditional compilation features analagous to those of C/C++. You can use the #if statement with a compilation directive like DEBUG to accomplish this.
#if DEBUG
public readonly string DebugUID = Guid.NewGuid().ToString();
#endif

Since by default only "Debug" configurations define the DEBUG directive, this will only compile in Debug mode. In Release mode the code inside the #if will be ignored.

A: Try using the "preprocessor" directive #if:
class Value {

#if DEBUG
private readonly string DebugUID = Guid.NewGuid().ToString()
#endif

}

You will have to make sure, though, that the DEBUG flag is set for debugging builds (and of course, unset for release builds).

A: You could use a conditional preprocessor include
#if DEBUG
private readonly string debugId = Guid.NewGuid().ToString();
#endif


text:
Q: Does the kinetic theory of gases means gases mix almost instantaneously? This theory has bugged me ever since my first physics class on the subject. If this (http://en.wikipedia.org/wiki/Kinetic_theory) is true, it leads me to a few weird conclusions.
Opening the rear window in a pickup truck at 10 m/s doesn't empty the cabin of all its air. This means that gas molecules can catch up with us from behind so we can conclude that gases move much faster than 10 m/s at normal temperatures.
Then, shouldn't gases mix almost instantaneously? For example, shouldn't a fart's smell reach us faster than a car on an highway and then dissapear almost immediately into such a large area that the concentration is too low for our noses to detect?

A: The kinetic theory of gases does in fact say that molecules in a gas move very rapidly (although some move quite slow, and others even faster).
However, there is another crucial component to the theory. The idea of Mean Free Path. Here, a molecule is moving very fast but doesn't get very far before hitting another molecule. This is why things like odors travel relatively slow and why gases don't "mix instantaneously." A given molecule may only move 1e-6 meters before bouncing off of another molecule, and the direction it bounces is random. This slows down the progress of mixing.
Additionally, in your example of opening the rear window of a truck, it's important to look at the macroscopic effects of the flow, which kinetic theory doesn't really explain. The truck cabin generates a wake with a recirculation zone behind it. This means that the air immediately behind the window is relatively stagnant, which is also why the air in the cabin doesn't leave as fast as it could.


text:
Q: How to create complex nifi processor for plc? I want to create a custom nifi processor, so I can read s7 plc data. To do this, I want to convert the java code of this project: https://github.com/s7connector/s7connector to a nifi processor.
So, I have download mvn package type, as this webiste tells to do:
https://medium.com/hashmapinc/creating-custom-processors-and-controllers-in-apache-nifi-e14148740ea
The problem is that s7 java code is too complex compared with the example on the web, so... How can I transform this java code to nifi processor?
Has someone a more complex code example of how to transform java to nifi processor?
Thanks!

A: It doesn't related to creating a processor but PLC4X (The universal protocol adapter for Industrial IoT) has created nar file for the Apache NiFi. Which you can use it for your end goal.
Steps:

*

*Download the nar file here

*Put it in the lib directory

*Restart the NiFi instance

*Then use PLC4XSource processor to read values. For modbus you may set "modbus:tcp://10.0.2.238:502?slave=1" as connetion string and "test1=holding-register:1" as address string. Then attribute "test1" will contain holding-register 1's value. You may get detailed info about S7 here.


text:
Q: Problems with vertical y-axis alignment I am trying to get the vertical axes aligned in the following figure but having trouble.  In particular, the y-axis of the first and last figure in the 3rd row have to be aligned with those of the previous rows. Other issues are:

*

*asterisk and the equal to signs are not at the center,

*the figures in the last column are not to scale, and

*the font is too big.

Thanks.

\documentclass[aspectratio=169,11pt]{beamer}
\mode<presentation>

\usepackage{pgfpages,mathtools}

\usepackage{pgfplots}
\usepackage{tikz}

\usetikzlibrary{arrows,plotmarks}
\usetikzlibrary{matrix}

\usetheme{Boadilla}
\date{}

\begin{document}

\begin{frame}
  \frametitle{Examples}
  \begin{tikzpicture}[ampersand replacement=\&,baseline=(current bounding box.center)]
  \matrix{
    \begin{axis}[axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (conv1) {$\ast$};

   \&\begin{axis}[%
     axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (equal1) {$=$};

   \&\begin{axis}[%
     axis lines=middle, xtick={0,4,8},
     xticklabels={0,$T$,$2T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$T$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none]
     coordinates
     {(0,0) (4,1) (8,0)};
   \end{axis}\\

   \begin{axis}[axis lines=middle, xtick={0,8},
     xticklabels={0,$2T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (8,0)};
   \end{axis}

   \& \node (conv2) {$\ast$};

   \&\begin{axis}[axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (equal2) {$=$};

   \&\begin{axis}[axis lines=middle, xtick={0,4,8,12},
     xticklabels={0,$T$,$2T$,$3T$},ymin=0, ymax=1.2,
     xmin=0,xmax=13,ytick={1},yticklabels={$T$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none]
     coordinates
     {(0,0) (4,1) (8,1) (12,0)};
   \end{axis}\\

   \begin{axis}[axis lines=middle, xtick={-4,0},
     xticklabels={$-T$,0},ymin=0, ymax=1.2,
     xmin=-5,xmax=5,ytick={1},yticklabels={$1$},
     height=3cm,
     y tick label style={anchor=west},
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(-4,0) (-4,1) (0,0)};
   \end{axis}

   \& \node (conv3) {$\ast$};

   \&\begin{axis}[axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (equal3) {$=$};

   \&\begin{axis}[axis lines=middle, xtick={-4,0,4},
     xticklabels={$-T$,$0$,$T$},ymin=0, ymax=1.2,
     xmin=-5,xmax=5,ytick={1},yticklabels={$T$},
     height=3cm,
     xlabel={\empty}, x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west}]
     \addplot+[very thick,mark=none]
     coordinates
     {(-4,0) (0,1) (4,0)};
   \end{axis}\\
 };
\end{tikzpicture}%
\end{frame}

\end{document}

A: If you add
every axis/.append style={
footnotesize,
height=3cm,
unit vector ratio=1 4 1,
execute at end axis={
   \coordinate (O) at (current axis.east -| current axis.origin);
   },
anchor=O,

to the tikzpicture options, you get

Does that look better? (The common settings added in the every axis style is removed from the individual axes.)
Note also that xlabel=\empty is kind of strange. The \empty macro is intended for ticks (xtick/ytick/ztick), for the case where you don't want any ticks at all. If you don't need an xlabel, just remove xlabel=.. altogether. (And then you can also remove the x label style of course.)
\documentclass[aspectratio=169,11pt]{beamer}
\mode<presentation>

\usepackage{pgfpages,mathtools}

\usepackage{pgfplots}

\usetikzlibrary{arrows,plotmarks}
\usetikzlibrary{matrix}

\usetheme{Boadilla}
\date{}

\begin{document}

\begin{frame}
  \frametitle{Examples}
  \begin{tikzpicture}[
   ampersand replacement=\&,
   baseline=(current bounding box.center),
   every axis/.append style={
    footnotesize,
    height=3cm,
    unit vector ratio=1 4 1,
    execute at end axis={
       \coordinate (O) at (current axis.east -| current axis.origin);
       },
    anchor=O
    }
   ]
  \matrix{
    \begin{axis}[axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     ]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (conv1) {$\ast$};

   \&\begin{axis}[%
     axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     ]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (equal1) {$=$};

   \&\begin{axis}[%
     axis lines=middle, xtick={0,4,8},
     xticklabels={0,$T$,$2T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$T$},
     ]
     \addplot+[very thick,mark=none]
     coordinates
     {(0,0) (4,1) (8,0)};
   \end{axis}\\

   \begin{axis}[axis lines=middle, xtick={0,8},
     xticklabels={0,$2T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     ]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (8,0)};
   \end{axis}

   \& \node (conv2) {$\ast$};

   \&\begin{axis}[axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     ]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (equal2) {$=$};

   \&\begin{axis}[axis lines=middle, xtick={0,4,8,12},
     xticklabels={0,$T$,$2T$,$3T$},ymin=0, ymax=1.2,
     xmin=0,xmax=13,ytick={1},yticklabels={$T$},
     ]
     \addplot+[very thick,mark=none]
     coordinates
     {(0,0) (4,1) (8,1) (12,0)};
   \end{axis}\\

   \begin{axis}[axis lines=middle, xtick={-4,0},
     xticklabels={$-T$,0},ymin=0, ymax=1.2,
     xmin=-5,xmax=5,ytick={1},yticklabels={$1$},
     y tick label style={anchor=west},
     ]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(-4,0) (-4,1) (0,0)};
   \end{axis}

   \& \node (conv3) {$\ast$};

   \&\begin{axis}[axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},ymin=0, ymax=1.2,
     xmin=0,xmax=10,ytick={1},yticklabels={$1$},
     ]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \& \node (equal3) {$=$};

   \&\begin{axis}[axis lines=middle, xtick={-4,0,4},
     xticklabels={$-T$,$0$,$T$},ymin=0, ymax=1.2,
     xmin=-5,xmax=5,ytick={1},yticklabels={$T$},
     ]
     \addplot+[very thick,mark=none]
     coordinates
     {(-4,0) (0,1) (4,0)};
   \end{axis}\\
 };
\end{tikzpicture}%
\end{frame}
\end{document}

A: Here a solution to center \ast and = symbols between plots

*

*First you need to name plots with name= A,B,...,I.

*Then you can place nodes containing \ast and = symbols like this

 \foreach \i/\j in {A/B,D/E,G/H}
{\path (\i.south east)--node{$\ast$}(\j.south west);}
\foreach \i/\j in {B/C,E/F,H/I}
{\path (\i.south east)--node{$=$}(\j.south west);}

Complete Code
\documentclass[aspectratio=169,11pt]{beamer}
\mode<presentation>

\usepackage{pgfpages,mathtools}

\usepackage{pgfplots}

\usetikzlibrary{arrows,plotmarks}
\usetikzlibrary{matrix}

\usetheme{Boadilla}
\date{}

\begin{document}

\begin{frame}
  \frametitle{Examples}
  \begin{tikzpicture}[ampersand replacement=\&,baseline=(current bounding box.center),
  every axis/.append style={ymin=0, ymax=1.2,height=3cm,
     font=\scriptsize,xlabel={\empty},
     x label style={anchor=north},
     ylabel={\empty}, y label style={anchor=west},
     axis lines=middle,,xmin=0,xmax=10}]

  \matrix[column sep=3mm]{
    \begin{axis}[name=A,axis lines=middle, xtick={0,4},
     xticklabels={0,$T$},yticklabels={$1$},ytick={1}]
          \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \&

   \&\begin{axis}[%
     name=B, xtick={0,4},
     xticklabels={0,$T$},ytick={1},yticklabels={$1$}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \&

   \&\begin{axis}[%
     name=C, xtick={0,4,8},
     xticklabels={0,$T$,$2T$},ytick={1},yticklabels={$T$}]
     \addplot+[very thick,mark=none]
     coordinates
     {(0,0) (4,1) (8,0)};
   \end{axis}\\

   \begin{axis}[name=D, xtick={0,8},
     xticklabels={0,$2T$},ytick={1},yticklabels={$1$}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (8,0)};
   \end{axis}

   \&

   \&\begin{axis}[name=E, xtick={0,4},
     xticklabels={0,$T$},
     ytick={1},yticklabels={$1$}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \&

   \&\begin{axis}[name=F, xtick={0,4,8,12},
     xticklabels={0,$T$,$2T$,$3T$},
     xmax=13,ytick={1},yticklabels={$T$}]
     \addplot+[very thick,mark=none]
     coordinates
     {(0,0) (4,1) (8,1) (12,0)};
   \end{axis}\\

   \begin{axis}[name=G, xtick={-4,0},
     xticklabels={$-T$,0},
     xmin=-5,xmax=5,ytick={1},yticklabels={$1$}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(-4,0) (-4,1) (0,0)};
   \end{axis}

   \&

   \&\begin{axis}[name=H, xtick={0,4},
     xticklabels={0,$T$},ytick={1},yticklabels={$1$}]
     \addplot+[very thick,mark=none,const plot]
     coordinates
     {(0,0) (0,1) (4,0)};
   \end{axis}

   \&

   \&\begin{axis}[name=I, xtick={-4,0,4},
     xticklabels={$-T$,$0$,$T$},
     xmin=-5,xmax=5,ytick={1},yticklabels={$T$}]
     \addplot+[very thick,mark=none]
     coordinates
     {(-4,0) (0,1) (4,0)};
   \end{axis}\\
 };

 \foreach \i/\j in {A/B,D/E,G/H}
{\path (\i.south east)--node{$\ast$}(\j.south west);}
\foreach \i/\j in {B/C,E/F,H/I}
{\path (\i.south east)--node{$=$}(\j.south west);}
\end{tikzpicture}%
\end{frame}

\end{document}


text:
Q: 301 redirect regex for file paths to uploads directory I am moving a website to wordpress and the site has hundreds of files available for download. The current file path may have a number of subfolders before the name of the file. Below are some examples of how a url may look.
"http://www.example.com/uploads/folder/subfolder/anothersubfolder/file.pdf"

"http://www.example.com/uploads/folder/file.pdf"

  "http://www.example.com/uploads/folder/subfolder/anothersubfolder/anothersubfolder/file.doc"

I want to create a 301 redirect to handle any requests for these files and send them to the new url which would be
"http://www.example.com/wp-content/uploads/folder/subfolder"

I'm keeping the sub-folders the same in the uploads folder, so really I need a regex for pointing anything that goes to
"http://www.example.com/uploads/"

and point it to
"http://www.example.com/wp-content/uploads/"

Update
My current .htaccess file looks like
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I've tried adding the answer from anubhava within the <IfModule mod_rewrite.c> block but I think there is an issue with the RewriteBase / from wordpress and me trying to add RewriteBase /uploads/. How can I have a rewrite condition for the /uploads directory?

A: You can use this redirect rule in DocumentRoot/.htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>

RewriteEngine On
RewriteBase /

RewriteRule ^uploads(.*)$ /wp-content/uploads/$1 [L,NE,R=301]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

</IfModule>
# END WordPress


text:
Q: No sé como empezar a programar en C++ Me han dejado este ejercicio, pero no sé como empezar a realizarlo y no tengo casos de prueba ni ejemplos. Creo que podría usar punteros. Pero no estoy empapada del todo.

Programe la colisión entre estos 4 planetas. Las colisiones son por pares de planetas. Cualquier planeta puede colisionar con otro, si la distancia entre ellos (aleatorio entre 0 y 30) es menor a 0.5. No necesita considerar distancias reales entre planetas, sino usar un numero random para decidir si hay colisión.
Luego de la colisión, el planeta más pesado sobrevive, y se le suma la mitad de la masa del otro planeta (hay perdida de masa por la colisión). Además, su diámetro se duplica.

Tomé como datos, los siguientes pesos y diámetros, en unidades de masa/diámetro terrestre ( porque según yo son los más famosos):
Mercurio (0.05 masa terrestre, diámetro 0.4)
Venus (0.8 masa terrestre, diámetro 0.9)
Tierra (1 masa terrestre, diámetro 1)
Marte (0.1 masa terrestre, diámetro 0.5)
tengo esta parte del código que hice, pero no logro encontrar una forma de empezar...
/*. sistema solar.*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
  int A,B,planetas;
  cout <<"Elegir los planetas a colisionar: "<<endl;
  cout<<"1) marte"<<endl;
  cout<<"2) tierra"<<endl;
  cout<<"3) mercurio"<<endl;
  cout<<"4) venus"<<endl;
  cin>>planetas;
  if tierra distancia > 0.5{

  }

}

void distancia(){
  int distancia;
  srand(time(NULL));
  num=rand()%31;
  return distancia;
}
void tierra(){
  int masa = 1;
  int diametro = 1
  while diametro >
}

A: //codigo

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <list>

using namespace std;

#define ARRIBA 72
#define IZQUIERDA 75
#define DERECHA 77
#define ABAJO 80

void situarCursor(int x, int y)
{
 HANDLE hCon;
 hCon=GetStdHandle(STD_OUTPUT_HANDLE);
 COORD cPunto;
  cPunto.X=x;
  cPunto.Y=y;
  SetConsoleCursorPosition(hCon,cPunto);
 }

  void ocultarCursor()
 {
 HANDLE hCon;
 hCon=GetStdHandle(STD_OUTPUT_HANDLE);
 CONSOLE_CURSOR_INFO cInfo;
 cInfo.dwSize=2;
 cInfo.bVisible=FALSE;
 SetConsoleCursorInfo(hCon,&cInfo);
 }
  void pintarLimites()
 {
 for(int i=2; i<78;i++)
 {
  situarCursor(i,2); printf("%c",205);
  situarCursor(i,33); printf("%c",205);
 }
 for(int i=3; i<33;i++)
 {
  situarCursor(2,i); printf("%c",186);
  situarCursor(77,i); printf("%c",186);
 }
  situarCursor(2,2); printf("%c",201);
  situarCursor(2,33); printf("%c",200);
  situarCursor(77,2); printf("%c",187);
  situarCursor(77,33); printf("%c",188);
 }

 class NAVE
{
 int x,y;
 int corazones;
 int vidas;
 public:
  NAVE(int _x, int _y, int _corazones, int
 _vidas):x(_x),y(_y), corazones(_corazones),
  vidas(_vidas){}
  void pintar();
  void borrar();
  void mover();
  void pintarCorazones();
  void morir();
  void restarCorazon(){corazones--;}
  int X(){return x;}
  int Y(){return y;}
  int VIDAS(){return vidas;}
};

void NAVE::pintar()
{
  situarCursor(x,y);printf("  %c",30);
  situarCursor(x,y+1);printf(" %c%c%c",40,207,41);
  situarCursor(x,y+2);printf("%c%c %c%c",30,190,190,30);
}
void NAVE::borrar()
{
 situarCursor(x,y);printf("          ");
 situarCursor(x,y+1);printf("          ");
 situarCursor(x,y+2);printf("          ");
}

void NAVE::mover()
{
 if(kbhit())
  {
   char tecla=getch();
   borrar();
   if(tecla==IZQUIERDA && x>3){x--;}
   if(tecla==DERECHA && x+6<78){x++;}
   if(tecla==ARRIBA && y>3){y--;}
   if(tecla==ABAJO && y+3<33){y++;}
   pintar();

  }
}

void NAVE::pintarCorazones()
{

 situarCursor(50,1);
 printf("Vidas: %d", vidas);

 situarCursor(64,1);
 printf("Salud");
 situarCursor(70,1);
 printf("       ");
 for(int i=0; i<corazones;i++)
 {
   situarCursor(70+i,1);
   printf("%c",3);
 }

 }

 void NAVE::morir()
 {
   if(corazones==0)
 {
   borrar();
  situarCursor(x,y);   printf("   **   ");
  situarCursor(x,y+1); printf("  ***  ");
  situarCursor(x,y+2); printf("   **   ");
  Sleep(200);
  borrar();
  situarCursor(x,y);   printf(" * ** * ");
  situarCursor(x,y+1); printf("* *** *");
  situarCursor(x,y+2); printf("* ** *");
  Sleep(200);
   borrar();
   vidas--;
   corazones=3;
   pintarCorazones();
   pintar();
 }
}

class AST
{
 int x,y;
public:
 AST(int _x, int _y):x(_x),y(_y){}
 void pintar();
 void mover();
 void choque(class NAVE &N);
 int X(){return x;}
 int Y(){return y;}
};

void AST::choque(class NAVE &N)
{
 if(x>=N.X() && x<= N.X()+5 && y>=N.Y() && y<=N.Y()+2)
 {
  N.restarCorazon();
  N.pintar();
  N.pintarCorazones();
  x=rand()%71+4;
  y=4;
 }
}

 void AST::pintar()
{
 situarCursor(x,y);printf("%c",184);

}
void AST::mover()
{
 situarCursor(x,y);printf(" ");
 y++;
 if(y>32)
 {
  x=rand()%71+4;
  y=4;
 }
 pintar();
}

class BALA
{
 int x,y;
public:
 BALA(int _x, int _y):x(_x),y(_y){}
 void mover();
 bool fuera();
 int X(){return x;}
 int Y(){return y;}

 };

void BALA::mover()
{
 situarCursor(x,y); printf(" ");
 if(y>3){y--;}
 situarCursor(x,y); printf("*");
}

bool BALA::fuera()
 {
 if(y==3)
 {
  return true;
 }
 return false;
}

int main()
{
 int puntos=0;
 pintarLimites();
 ocultarCursor();
 NAVE N(38,30,3,5);
 N.pintar();
 N.pintarCorazones();

 list<AST*> A;
 list<AST*>::iterator Ait;

 for(int i=0; i<5;i++)
 {
  A.push_back(new AST(rand()%75+3, rand()%5+4));
 }

 list<BALA*> B;
 list<BALA*>::iterator it;

 bool game_over=false;
 while (!game_over)
 {

  situarCursor(4,2); printf("Puntos: %d",puntos);

  if(kbhit())
  {
   char tecla=getch();
   if(tecla=='c')
   {
    B.push_back(new BALA(N.X()+2,N.Y()-1));
   }
  }

  for(it=B.begin(); it!=B.end();)
  {
   (*it)->mover();
   if((*it)->fuera())
  {
    situarCursor((*it)>X(),(*it)>Y());
    printf(" ");
    delete(*it);
    it=B.erase(it);
   }
   else it++;

  }

  for(Ait=A.begin(); Ait!=A.end(); Ait++ )
  {
   (*Ait)->mover();
   (*Ait)->choque(N);
  }

  //detectar colisiones entre bala y asteroides
  for(Ait=A.begin(); Ait!=A.end();Ait++)
  {
   for(it=B.begin(); it!=B.end(); )
   {
    if((*Ait)>X()==(*it)>X() && ( (*Ait)>Y()+1==(*it)>Y()
||
    (*Ait)>Y()==(*it)>Y()))
    {
     situarCursor((*it)>X(),(*it)>Y());printf(" ");
     delete(*it);
     it=B.erase(it);

     A.push_back(new AST(rand()%75,3));
     situarCursor((*Ait)>X(),(*Ait)>Y());printf(" ");
     delete(*Ait);
     Ait=A.erase(Ait);
     puntos+=5;

    }
    else
    {
     it++;
    }
   }

  }

  if(N.VIDAS()==0)
  {
   game_over=true;
  }

  N.morir();
  N.mover();
  Sleep(30);

 }

    return 0;
 }


text:
Q: PowerShell Exporting to CSV / Workflow? When the server is ping'd the resulting address is compared to an inventory for purposes of keeping the inventory up to date.
I'm trying to tack on the result as "good" or "bad" in the next corresponding cell over. It sort of works except the result is always "bad" with the workflow I have set up.
The CSV contains the server name and IP address pulled from an excel inventory, and is formatted like this:
name,ipaddress
server1,10.1.24.51
server2,10.1.24.52
server3,10.1.24.53
server4,10.1.27.101
server5,10.1.27.102 <--- purposely wrong IP address for testing

Current script:
$serverlist = Import-Csv -Path file.csv

ForEach ($server in $serverlist) {

    $thisservername = $server.name
    $thisserveripaddress = $server.ipaddress

    $pingdaddress = (Test-Connection -ComputerName $thisservername -Count 1 -ErrorAction SilentlyContinue -Verbose).IPV4Address.IPAddressToString

    if ($pingdaddress -ne $thisserveripaddress) {

        #$thisservername + " bad"
        $serverlist | Select-Object name,ipaddress, @{Name='connection';Expression={'bad'}} | `
        Export-Csv -Path file.csv -NoTypeInformation

    } else {

        #$thisservername + " good"
        $serverlist | Select-Object name,ipaddress, @{Name='connection';Expression={'good'}} | `
        Export-Csv -Path file.csv -NoTypeInformation

    }

}

A: I think your error is stemming from $pingdaddress = (Test-Connection -ComputerName $thisservername -Count 1 -ErrorAction SilentlyContinue -Verbose).IPV4Address.IPAddressToString. If the server name cannot be resolved, the connection object (well, Win32_PingStatus object) returned by Test-Connection will be $null. You then are trying to access a property on a null object, which isn't allowed.
I would split the 'success' portion into it's own column. You can do this by adding another column to your CSV, e.g.: NameMatch or IPMatch, whatever makes more sense to you. This way you can access it as a property in your loop $server.NameMatch and do filtering/sorting on the data later.
function Test-ServerNameMapping
{

    [cmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateScript({Test-Path $_})]
        [String]
        $Path
    )

    $serverList = Import-Csv -Path $Path

    foreach ($server in $serverList)
    {
        Write-Verbose "Testing: $($server.Name), $($server.IPAddress)"

        $connectionObject = (Test-Connection -ComputerName $server.Name -Count 1 -ErrorAction SilentlyContinue)

        if (-not $connectionObject)
        {
            Write-Verbose "Failed to resolve $($server.Name) to an IP address."
            $server.namematch = $false
        }
        else
        {
            $resolvedAddress = $connectionObject.IPV4Address.ToString()
            Write-Verbose "Resolved $($server.Name) to $resolvedAddress"

            if ($resolvedAddress -eq $server.IPAddress)
            {
                Write-Verbose "$($server.IPAddress) matches found address of $resolvedAddress"
                $server.namematch = $true
            }
            else
            {
                Write-Verbose "$($server.IPAddress) does not equal found address of $resolvedAddress"
                $server.namematch = $false
            }
        }
    }

    $serverList | Export-Csv -Path $Path -NoTypeInformation -Force

}

Then if you wanted to produce a report later you could do something like:
$problemServers = Import-Csv -Path c:\example.csv | ? NameMatch -eq $false

Example.csv:
Name,IPAddress,NameMatch
server1,10.0.0.1,"True"
server2,10.0.0.2,
server3,10.0.0.3,"False"

When you first run the script, the NameMatch column can be empty (as it is with server2), and the script will fill it in.


text:
Q: UITabBar selected tint color I need to change uitabbar selected tint color from blue to yellow. How can i do it??? Can any one help me with this??

A: Here's a good starting point: how to change UITabbar selected color?


text:
Q: RAID 5 virtual disk still shows up as degraded after repair On a machine running Windows Server 2012 R2, I have a virtual disk consisting of 8 physical disks in a RAID-5 configuration. One drive died, so I replaced the dead drive and followed these instructions for repairing the virtual disk: Replacing a Failed Disk in Windows Server 2012 R2 Storage Spaces with PowerShell.
Everything seemed to be working great, with one discrepancy: despite completing the whole repair process with no errors, the virtual disk still is marked as "degraded", even though it once again has 8 healthy drives. What gives?
The file system on the virtual drive (which is backed up) is still accessible, but I'd like to know if I again have resiliency against a drive failure or not, but I can't find any information about why the virtual disk is still degraded, or how to determine if it really is degraded, or how to fix it.
Here is some powershell output that I hope will be useful. Thank you!

And again as text:
PS C:\Users\Administrator> Get-StoragePool

FriendlyName            OperationalStatus       HealthStatus            IsPrimordial            IsReadOnly
------------            -----------------       ------------            ------------            ----------
Z                       OK                      Healthy                 False                   False
Primordial              OK                      Healthy                 True                    False

PS C:\Users\Administrator> Get-VirtualDisk

FriendlyName        ResiliencySettingNa OperationalStatus   HealthStatus        IsManualAttach                     Size
                    me
------------        ------------------- -----------------   ------------        --------------                     ----
Z                   Parity              Degraded            Warning             False                          25.46 TB

PS C:\Users\Administrator> $zdisk = Get-VirtualDisk | Where-Object { $_.FriendlyName -eq 'Z' }
PS C:\Users\Administrator> Get-PhysicalDisk -VirtualDisk $zdisk

FriendlyName        CanPool             OperationalStatus   HealthStatus        Usage                              Size
------------        -------             -----------------   ------------        -----                              ----
PhysicalDisk5       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk1       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk2       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk7       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk6       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk8       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk3       False               OK                  Healthy             Auto-Select                     3.64 TB
PhysicalDisk4       False               OK                  Healthy             Auto-Select                     3.64 TB

PS C:\Users\Administrator>

In case it matters, PhysicalDisk4 is the new replacement disk that I added to replace the dead disk.
Note that I'm cross-posting this from superuser after waiting a while for answers. Not sure if that's against protocol around here - I'll delete the other post if that's the done thing.


text:
Q: How to get specific fields or update theme and get the relation fildes from api calls in yii2 REST API? I'm trying default yii2 api rest calls GET to get some model fields or PUT to update some model fields but I can't find a way to do this. I can only get all the fields or update theme all. Any help to do this? And how can I get the related relational field to this model?
I'm trying like this like
GET localhost/my-website-name/api/web/v1/vendors/
PUT localhost/my-website-name/api/web/v1/vendors/1

A: one way that I know for customizing fields is overriding fields function in your model like this
   public function fields() {
   return [
       'id',
        'iso3' => function() {
           return base64_encode($this->iso3);
       }
   ];
}

A:
How to get specific fields and get the relation fields from api calls?

By default, yii\db\ActiveRecord::fields() returns all model attributes which have been populated from DB as fields, while yii\db\ActiveRecord::extraFields() should return the names of model's relations.
Take this model for example:
class Image extends ActiveRecord
{
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'owner_id' => 'Owner ID',
            'name' => 'Name',
            'url' => 'Url',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getOwner()
    {
        return $this->hasOne(Owner::className(), ['id' => 'owner_id']);
    }

    public function extraFields()
    {
        return ['owner'];
    }
}

Here I did override the extraFields() method to define the owner relationship. Now if I want to retreive all images but selecting id and name fields only and each resource should also hold its related owner data I would simply request this url:
GET example.com/images?fields=id,name&expand=owner

*

*note: you can also use comma separation to expand more than one relation
In case you want to permanently remove some fields like created_at and updated_at you can also override the fields() method:
public function fields()
{
    $fields = parent::fields();
    unset($fields['created_at'], $fields['updated_at'], $fields['owner_id']);
    return $fields;
    /*
        // or could also be:
        return ['id', 'name','url'];
    */
}

this way the following request should only return image's id, name and url fields along with their related owner :
GET example.com/images?expand=owner

If owner's fields should be filtered too then override its fields() method too in its related class or a child class of it that you tie to the image model by using it when defining the relation.
See official documentation for further details.

PUT to update some model fields

Yii only updates dirty attributes. so when doing:
PUT example.com/images/1 {"name": "abc"}

the generated SQL query should only update the name column of id=1 inside database.

A: Hello i manage to find a solution for this situations

*

*first get some model fields only and with related entities fildes:
public function fields() {
return [
    'name',
    'phone_number',
    'minimum_order_amount',
    'time_order_open',
    'time_order_close',
    'delivery_fee',
    'halal',
    'featured',
    'disable_ordering',
    'delivery_duration',
    'working_hours',
    'longitude',
    'latitude',
    'image',
    'owner' => function() {
        $owner = Owners::findOne($this->owner_id);
        return array($owner);
    }
 ];
}

*if you want to remove some fildes
public function fields()
{
  $fields=parent::fields();
  unset($fields['id']);
  return $fields;
}

*update only specific fields
public function beforeSave($insert)
 {
  $lockedValues = ['name', 'halal', 'featured', 'latitude', 'longitude', 'image', 'status', 'created_at', 'updated_at'];
    foreach ($lockedValues as $lockedValue) {
      if ($this->attributes[$lockedValue] != $this->oldAttributes[$lockedValue])
        throw new ForbiddenHttpException($lockedValue . " can't be changed.");
  }

return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}


text:
Q: docker swarm: how to publish a service only on a specific node that runs a task I created a docker-compose.yml file containing two services that are run on two different nodes. The two services are meant to communicate on the same port as client and server. Below is my docker-compose.yml file.
 version: "3"
services:
  service1:
    image: localrepo/image1
    deploy:
      placement:
        constraints: [node.hostname == node1]
      replicas: 1
      resources:
        limits:
          cpus: "1"
          memory: 1000M
      restart_policy:
        condition: on-failure
    ports:
      - 8000:8000
    networks:
      - webnet

  service2:
    image: localrepo/image2
    deploy:
      placement:
        constraints: [node.hostname == node2]
      replicas: 1
      resources:
        limits:
          cpus: "1"
          memory: 500M
      restart_policy:
        condition: on-failure
    ports:
      - "8000:8000"
    networks:
      - webnet
networks:
  webnet:

When I issue docker stack deploy -c I get error, reading
> Error response from daemon: rpc error: code = 3 desc = port '8000' is already in use by service.

In this thread I read that deploying a service in a swarm makes the port accessible throughout any node in the swarm.  If I understand correctly, that makes the port occupied by any node in the cluster. In the same thread, it was suggested to use mode=host publishing, which will only expose the port on the actual host that the container runs. I applied that in the port as:
ports:
  - "mode=host, target=8000, published=8000"
Making that change in both service and trying to issue docker stack gives another error:
> 1 error(s) decoding:

* Invalid containerPort: mode=host, target=8000, published=8000

Does anyone know how to fix this issue?
p.s: I tried both "Version3" and "Version3.2" but the issue didn't solve.

A: I don't know how did you specify host mode since your docker-compose.yml doesn't represent host mode anywhere.
Incidentally, try with long syntax which can specify host mode in docker-compose.yml file.
This long syntax is new in v3.2 and the below is the example(I check it works)
(This is compatible docker engine version against docker-compose syntax version.)
version: '3.4'     # version: '3.2' also will works

networks:
    swarm_network:
        driver: overlay

services:
    service1:
        image: asleea/test

        command: ["nc", "-vlkp", "8000"]

        deploy:
            mode: replicated
            replicas: 1
            placement:
                constraints:
                    - node.hostname == node1

        ports:
            - published: 8000
              target: 8000
              mode: host

        networks:
            swarm_network:

    service2:
        image: asleea/test

        command: ["nc", "service1", "8000"]

        deploy:
            mode: replicated
            replicas: 1
            placement:
                constraints:
                    - node.hostname == node2

        ports:
            - published: 8000
              target: 8000
              mode: host

        networks:
            swarm_network:

A: The problem is fixed after upgrading to the latest docker version, 18.01.0-ce


text:
Q: PredicateBuilder and LINQ to CRM I'm trying to pull all the instances of a workflow that have ran (from the AsyncOperationBase table) with a number of predicates.
I know you can't use something like myArray.Contains(x.WorkflowActivationId.Id) so I'm trying to build a predicate dynamically with PredicateBuilder
Here's what I have so far:
var predicate = PredicateBuilder.False<Service.AsyncOperation>();

//Apparently, checking for null is suppose to prevent my issue from happening...
predicate = predicate.And(x => x.Name == searchWorkflowDefinitionText.Text);
predicate = predicate.And(x => x.StatusCode != null);
predicate = predicate.And(x => x.StatusCode.Value == 10);
predicate = predicate.And(x => x.WorkflowActivationId != null);

foreach (Guid s in listBox3.Items)
{
    predicate = predicate.Or(x => x.WorkflowActivationId.Id == s);
}

var r = (from c in xrm.CreateQuery<Service.AsyncOperation>().AsExpandable().Where(predicate)
                         select c).ToList();

But I end up getting the much LINQ to CRM dreaded exception:
Invalid 'where' condition. An entity member is invoking an invalid property or method.

As far as I know, to not get this error, you need to 'crawl down' attributes. Things like:
predicate = predicate.Or(x => x.WorkflowActivationId == s);

Have to be changed to
predicate = predicate.Or(x => x.WorkflowActivationId.Id == s);

And also, the left hand side of the predicate must be a entity attribute. Again, as far as I know, my predicate satisfies those requirements so I am a bit at a loss here.
Any ideas ?

A: I think I will need to circumvent LINQ to CRM's limits by doing this 2 part.
1st:
var t = xrm.AsyncOperationSet.Where(x => x.StatusCode.Value == 10 && x.Name == wkname).Select(y => new Service.AsyncOperation
                {
                    AsyncOperationId = y.AsyncOperationId.Value,
                    WorkflowActivationId = y.WorkflowActivationId
                }).ToList();

I really need only these two attributes for the moment.
Then I'll be able to have full LINQ access to t's content.
var y = t.Where(x => myArray.Contains(x.WorkflowActivationId.Id)).ToList();


text:
Q: Вывод через пробел Python Ума не приложу, как правильно вывести массив типа integer в виде строки через пробел? Есть варианты? Массив вида:
z = [1,2,3,4,5,6,7]

A: print " ".join(map(str, z))

A: for i in z: print(i, end = " ")

A: print ' '.join(z)

A: print ' '.join(str(v) for v in z)


text:
Q: Make divs width oscillate between a given range before breaking on to new line? I have a parent div with two children inside.

content

I want the a href to be floated left and be 100% of the image's size (655px X 506px).  I want the sidebar to be floated left and stay inline with the a href as long as it's width is between 33.5% and 27%.  Then, once the width is smaller, I want the div to break onto a new line and be 100%.
Is there a way to make a divs width oscillate between a given range before having it break on to a new line without having to use multiple media queries?
Below is the css:
#middleHolder > a {
  float: left;
  margin: 0 2% 2% 0;
  max-width: 655px;
  width: 100%;
  }

#socialMediaSidebar {
  float: left
  min-height: 506px;
  min-width: 270px;
  width: 27-33.5%;  /* Not accurate, but gives the idea of what I'm trying to accomplish */
  }

  @media width… /*unsure the specific size but would be inacted once socialMediaSidebar goes less then 270px. */

#socialMediaSidebar {
  width: 100%;
  }

A: You can utilize max-width and min-width together to ensure that it will stay within a given range. Based on the model, if the content will not fit, it should display: block and drop down a line if the given range will not fit in the flow of the document.
Example could be:
#test {
    min-width: 25%;
    max-width: 37%;
    background: #CBA;
}

As seen here:
http://jsfiddle.net/e4j78ek6/1/


text:
Q: Makefile - Add objects to folder I don't understand why this works:
CC = gcc
CFLAGS = -fPIC
LDFLAGS = -shared
SRC = src/file.c
OBJ := $(SRC:.c=.o)

test: $(OBJ)
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

And this doesn't:
CC = gcc
CFLAGS = -fPIC
LDFLAGS = -shared
SRC = file.c
OBJ := $(addprefix output/, $(SRC:.c=.o))
SRC := $(addprefix src/, $(SRC))

test: $(OBJ)
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

As I'm only trying to make an output folder for all OBJ.
GCC tells me there's no rule to make "output/file.o" which leaves me perplex...

A: That's because there is a built-in rule that knows how to build X.o from X.c for any X, but there isn't a built-in rule that knows how to build output/X.o from src/X.c.  How could there be such a built-in rule, that knows about whatever special directory structure you come up with?
You'll have to define your own rule:
output/%.o : src/%.c
        $(COMPILE.c) $(OUTPUT_OPTION) $<


text:
Q: vmap gives inconsistent shape error when trying to calculate gradient per sample I am trying to implement a two layer neural network and get the gradient of the second layer per sample.
My code looks like this:
x = jnp.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=jnp.float32)
y = jnp.array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], dtype=jnp.float32)

W1 = jnp.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=jnp.float32)
W2 = random.uniform(key, shape=(10,), minval=1, maxval=2, dtype=jnp.float32)
b = jnp.linspace(0, -9, 10, dtype=jnp.float32)
b = jnp.reshape(b, (1,10))

def predict(W1, W2, b, x):
  f1 = jnp.einsum('i,j->ji', W1, x)+b
  f1 = nn.relu(f1)
  f2 = jnp.einsum('i,ji->j', W2, f1)
  return f2

def loss(W1, W2, b, x, y):
  preds = predict(W1, W2, b, x)
  return jnp.mean(jnp.square(y-preds))

perex_grads = vmap(grad(loss, argnums=1), in_axes= (0, None, 0, 0, 0))
pers_grads = perex_grads(W1, W2, b, x, y)

I ran loss and can do grad(loss) just fine. Running vmap is the actual problem.
The exact error I get is:
ValueError: vmap got inconsistent sizes for array axes to be mapped:
arg 0 has shape (10,) and axis 0 is to be mapped
arg 1 has shape (10,) and axis None is to be mapped
arg 2 has shape (1, 10) and axis 0 is to be mapped
arg 3 has shape (11,) and axis 0 is to be mapped
arg 4 has shape (11,) and axis 0 is to be mapped
so
arg 0 has an axis to be mapped of size 10
arg 2 has an axis to be mapped of size 1
args 3, 4 have axes to be mapped of size 11

It is my first time using Jax, and my google search didn't help me resolve the issue, plus the documentation was not very clear to me. I'd appreciate if anyone can help me.

A: The issue is exactly what the error message says: in order to vmap an operation over multiple arrays, the dimension of the mapped axes in each array must be equal. In your arrays, the dimensions are not equal: you passed in_axes=(0, None, 0, 0, 0) for arguments W1, W2, b, x, y, but W1.shape[0] = 10, b.shape[0] = 1, x.shape[0] = 11, and y.shape[0] = 11.
Because these are not equal, you get this error. To prevent this error, you should only vmap over array axes of the same length.
For example, if you want the gradients with respect to W2 computed per pair of W1, W2 inputs, it might look something like this (note the updated predict function and updated in_axes):
import jax.numpy as jnp
from jax import random, nn, grad, vmap

key = random.PRNGKey(0)

x = jnp.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=jnp.float32)
y = jnp.array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], dtype=jnp.float32)

W1 = jnp.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=jnp.float32)
W2 = random.uniform(key, shape=(10,), minval=1, maxval=2, dtype=jnp.float32)
b = jnp.linspace(0, -9, 10, dtype=jnp.float32)
b = jnp.reshape(b, (1,10))

def predict(W1, W2, b, x):
  # Since you're vmapping over W1 and W2, your function needs to
  # handle scalar values, so we cast to 1D if necessary.
  W1 = jnp.atleast_1d(W1)
  W2 = jnp.atleast_1d(W2)

  f1 = jnp.einsum('i,j->ji', W1, x)+b
  f1 = nn.relu(f1)
  f2 = jnp.einsum('i,ji->j', W2, f1)
  return f2

def loss(W1, W2, b, x, y):
  preds = predict(W1, W2, b, x)
  return jnp.mean(jnp.square(y-preds))

perex_grads = vmap(grad(loss, argnums=1), in_axes= (0, 0, None, None, None))
pers_grads = perex_grads(W1, W2, b, x, y)


text:
Q: Godot Firebase "Logout" method? So I am using Godot and firebase with RestAPI part, however I don't see a method or information on a way to "Logout" someone that has logged in with there credentials, after they log in, do whatever in the game, then "LOGOUT", if possible to clear there credentials, cache, or whatever.. I do have them going back to the main menu in the log in screen and clear the text boxes... but not sure if possible to make sure to clear it completely... is that possible?
thanks in advance

A: I was able to finally find a solution, looking at the godot firebase RestAPI, and calling https://firebase.google.com/docs/auth/web/password-auth, this is good.


text:
Q: Extract font-family and font-weight of @font-face from a CSS file I have a function that loops through all CSS files in directory and looks for @font-face.
if any @font-face block found, I want to extract font-family and font-weight from it.
the code below is what I've done so far:
function get_local_fonts() {
    $output = array();
    $path_to_search = trailingslashit(get_template_directory());
    foreach(glob_recursive($path_to_search . '*.css') as $file) {
        $content = file_get_contents($file);
        preg_match('/(\@font-face)([^}]+)(\})/', $content, $matches, PREG_OFFSET_CAPTURE);

        if (!empty($matches)) {
            preg_match('/(font-family:)([^;]*)/', $matches[2][0], $font_family, PREG_OFFSET_CAPTURE);
            preg_match('/(font-weight:)([^;]*)/', $matches[2][0], $font_weight, PREG_OFFSET_CAPTURE);

            $output[] = array(
                'file_path' => $file,
                'font-family' => trim($font_family[2][0]),
                'font-weight' => array(trim($font_weight[2][0])),
            );
        }
    }

    return $output;
}

this preg_match('/(\@font-face)([^}]+)(\})/', $content, $matches, PREG_OFFSET_CAPTURE); returns every CSS file that includes @font-face { ... }

my function works well with CSS files that only have one match for @font-face but let say if there are 4 matches for @font-face in a single CSS file my function only adds one of them.
for example (css file content):
@font-face
{
    font-family: "din";
    src: url("din-webfont.eot");
    src: url("din-webfont.eot?#iefix") format("embedded-opentype"),  url("din-webfont.woff") format("woff"), url("din-webfont.ttf") format("truetype");
    font-weight: normal;
    font-style: normal;
}
@font-face
{
    font-family: "din";
    src: url("din_bold-webfont.eot");
    src: url("din_bold-webfont.eot?#iefix") format("embedded-opentype"), url("din_bold-webfont.woff") format("woff"), url("din_bold-webfont.ttf") format("truetype");
    font-weight: bold;
    font-style: normal;
}

I want to get output like this:
Array
(
    [0] => Array
        (
            [font-family] => 'din'
            [font-weight] => Array
                (
                    [0] => 'normal',
                    [1] => 'bold'
                )

        )
)

Note that there might be @font-face with same font-family but different font-weight.

for conclusion:
How can I loop through All CSS files that contains
@font-face {
    font-family: something;
    font-weight: something;
}

and extract font-family and font-weight from them?

A: Use something like this:
$fontregex = '~@font-face[^}]*?font-family:\s*"([^"]+)"[^}]*?font-weight:\s*([^;]+);[^}]*?font-style:\s*([^;]+);~';
preg_match_all($fontregex, $mycss, $matches,PREG_SET_ORDER);
print_r($matches);

See the output at the bottom of the online php demo.
You'll have to fan the the result of $matches into a final array in a way that suits you.
Currently, here is the structure:
Array
(
    [0] => Array
        (
            [0] => @font-face
{
    font-family: "din";
    src: url("din-webfont.eot");
    src: url("din-webfont.eot?#iefix") format("embedded-opentype"),  url("din-webfont.woff") format("woff"), url("din-webfont.ttf") format("truetype");
    font-weight: normal;
    font-style: normal;
            [1] => din
            [2] => normal
            [3] => normal
        )

    [1] => Array
        (
            [0] => @font-face
{
    font-family: "din";
    src: url("din_bold-webfont.eot");
    src: url("din_bold-webfont.eot?#iefix") format("embedded-opentype"), url("din_bold-webfont.woff") format("woff"), url("din_bold-webfont.ttf") format("truetype");
    font-weight: bold;
    font-style: normal;
            [1] => din
            [2] => bold
            [3] => normal
        )

)


text:
Q: What is the best way to pull a remote file or folder from a PSSession (Enter-PSSession) I usually work in remote devices from Powershell
using the quick and useful 'Enter-PSSession'
it's a nice option...
replaces well a SSH console session...
and also has some advantages over SSH (has also disadvantages)
but...
I frequently need to TRANSFER A FILE OR A FOLDER (pull from remote)...
and found somewhat ANNOYING TO CREATE A NEW SESSION (new-session)
and re-enter credentials... etc. etc. ... just to make this copy..
?is there a MORE CONVENIENT APPROACH??
aka... a more easy way of doing this file-transfers
from inside the current session???
For reference, I'll leave  link to a discussion about this topic in a MS Forum...

A: Create the remote session with New-PSSession and use Copy-Item's -FromSession parameter:
$session = New-PSSession -ComputerName remoteComputer
Copy-Item C:\path\on\remote.ext -Destination C:\local\destination\ -FromSession $session

You can reuse $session for any subsequent copy operations from the same machine

Both commands have aliases that make this work with very few keystrokes:
$s = nsn remoteComputer
cp file.ext .\ -From $s


text:
Q: Why the OnEndDrag event is not called? I'm trying to detect the end of a drag & drop operation by using the TControl.OnEndDrag event.
It seems that the OnEndDrag event is never called when the DragObject parameter is assigned from the OnStartDrag event.
  TMyForm = class(TForm)
    procedure FormCreate(Sender: TObject);
  public
    MyLabel : TLabel;
    procedure MyOnEndDrag(Sender, Target: TObject; X, Y: Integer);
    procedure MyOnStartDrag(Sender: TObject; var DragObject: TDragObject);
  end;

procedure TMyForm.FormCreate(Sender: TObject);
begin
  MyLabel := TLabel.Create(Self);
  MyLabel.Caption := 'Drag me';
  MyLabel.Left := 50;
  MyLabel.Top := 50;
  MyLabel.OnStartDrag := MyOnStartDrag;
  MyLabel.OnEndDrag := MyOnEndDrag;
  MyLabel.DragMode := dmAutomatic;
  MyLabel.Parent := Self;
end;

procedure  TMyForm.MyOnEndDrag(Sender, Target: TObject; X, Y: Integer);
begin
  ShowMessage('MyOnEndDrag');
end;

procedure  TMyForm.MyOnStartDrag(Sender: TObject; var DragObject: TDragObject);
begin
  DragObject := TDragObjectEx.Create;
end;

I think the problem could be related to the DragObject's class but I don't understand what I'm doing wrong. How can I make sure the OnEndDrag event is called?

A: A drag object needs to know which control it should notify when the drag ends. The specialized class for this kind of operation in the VCL, that is a drag object that can be associated with a single control, is a TBaseDragControlObject. TDragControlObject[Ex] is the appropriate descendant which deals with dropping as opposed to its sibling TDragDockObject which deals with docking.
DragObject := TDragControlObjectEx.Create(MyLabel);


text:
Q: What is the fastest way to get k smallest (or largest) elements of array in Java? I have an array of elements (in the example, these are simply integers), which are compared using some custom comparator. In this example, I simulate this comparator by defining i SMALLER j if and only if scores[i] <= scores[j].
I have two approaches:

*

*using heap of the current k candidates

*using array of the current k candidates

I update the upper two structures in the following way:

*

*heap: methods PriorityQueue.poll and PriorityQueue.offer,

*array: index top of the worst among top k candidates in the array of candidates is stored. If a newly seen example is better than the element at the index top, the latter is replaced by the former and top is updated by iterating through all k elements of the array.

However, when I have tested, which of the approaches is faster, I found out that this is the second. The questions are:

*

*Is my use of PriorityQueue suboptimal?

*What is the fastest way to compute k smallest elements?

I am interested in the case, when the number of examples can be large, but the number of neighbours is relatively small (between 10 and 20).
Here is the code:
public static void main(String[] args) {
    long kopica, navadno, sortiranje;

    int numTries = 10000;
    int numExamples = 1000;
    int numNeighbours = 10;

    navadno = testSimple(numExamples, numNeighbours, numTries);
    kopica = testHeap(numExamples, numNeighbours, numTries);

    sortiranje = testSort(numExamples, numNeighbours, numTries, false);
    System.out.println(String.format("tries: %d examples: %d neighbours: %d\n time heap[ms]: %d\n time simple[ms]: %d", numTries, numExamples, numNeighbours, kopica, navadno));
}

public static long testHeap(int numberExamples, int numberNeighbours, int numberTries){
    Random rnd = new Random(123);
    long startTime = System.currentTimeMillis();
    for(int iteration = 0; iteration < numberTries; iteration++){
        final double[] scores = new double[numberExamples];
        for(int i = 0; i < numberExamples; i++){
            scores[i] = rnd.nextDouble();
        }
        PriorityQueue<Integer> myHeap = new PriorityQueue(numberNeighbours, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return -Double.compare(scores[o1], scores[o2]);
            }
        });

        int top;
        for(int i = 0; i < numberExamples; i++){
            if(i < numberNeighbours){
                myHeap.offer(i);
            } else{
                top = myHeap.peek();
                if(scores[top] > scores[i]){
                    myHeap.poll();
                    myHeap.offer(i);
                }
            }
        }

    }
    long endTime = System.currentTimeMillis();
    return endTime - startTime;
}

public static long testSimple(int numberExamples, int numberNeighbours, int numberTries){
    Random rnd = new Random(123);
    long startTime = System.currentTimeMillis();
    for(int iteration = 0; iteration < numberTries; iteration++){
        final double[] scores = new double[numberExamples];
        for(int i = 0; i < numberExamples; i++){
            scores[i] = rnd.nextDouble();
        }
        int[] candidates = new int[numberNeighbours];
        int top = 0;
        for(int i = 0; i < numberExamples; i++){
            if(i < numberNeighbours){
                candidates[i] = i;
                if(scores[candidates[top]] < scores[candidates[i]]) top = i;
            } else{
                if(scores[candidates[top]] > scores[i]){
                    candidates[top] = i;
                    top = 0;
                    for(int j = 1; j < numberNeighbours; j++){
                        if(scores[candidates[top]] < scores[candidates[j]]) top = j;
                    }
                }
            }
        }

    }
    long endTime = System.currentTimeMillis();
    return endTime - startTime;
}

This produces the following result:
tries: 10000 examples: 1000 neighbours: 10
   time heap[ms]: 393
   time simple[ms]: 388

A: Creating the fastest algorithm is never simple, you need to consider many things. For example the k elements need to be returned sorted or not, your research needs to be stable (if two elements are equals you need to extract before the first or is not necessary) or not?
In this contest theoretically the best solution is to save the k smallest element in an ordered data structure. Because insertion can happens often in the middle of this data structure a balanced sorted Tree seems to be an optimal solution.
But reality is very different from that.
Probably a mix between different data structure depending on the size of the original array and the value of k is the best solution:

*

*If k is little use an array to save the k smallest values

*If k is big use a balanced tree

*If k is very big and close to the dimension of the array, simply sort the array (and if you can't create a new sorted copy of it), then extract the first k elements.

This kind of algorithm is named hibryd algorithm. A famous hybrid algorithm is Tim Sort that is used in the java classes to sort collections.
Note: If you can use the power of multithreading different algorithms and so different data structures can be used.

Additional note on micro benchmark. Your performance measure can be strongly influenced by external factors not related to the efficiency of your algorithm. Creating objects, as you do in both functions, can need memory that is not available asking for an extra work done by the GC. This kind of factors influence very much you results. At least try to minimize code that is not strongly related to portion of code to be investigated. Repeat tests in different orders, Wait before invoking tests to be sure that no GC is in action.

A: First solution has time complexity O(numberExamples * log numberNeighbours), while second is O(numberExamples * numberNeighbours), so it has to be slower for large enough input. The second solution is faster because you test for small numberNeighbours, and PriorityQueue has bigger overhead that simple array.
You use PriorityQueue optimal.
Faster, but not optimal, would be just to sort an array, and then smallest elements is at k place.
Anyway you may want to implement QuickSelect algorithm, if you will choose pivot element smartly you should have better performance. You may want to see this https://discuss.leetcode.com/topic/55501/2ms-java-quick-select-only-2-points-to-mention

A: First of all, your benchmarking method is incorrect. You are measuring input data creation along with an algorithm performance, and you aren't warming up the JVM before measuring. Results for your code, when tested through the JMH:
Benchmark                     Mode  Cnt      Score   Error  Units
CounterBenchmark.testHeap    thrpt    2  18103,296          ops/s
CounterBenchmark.testSimple  thrpt    2  59490,384          ops/s

Modified benchmark pastebin.
Regarding 3x times difference between two provided solutions. In the terms of big-O notation your first algorithm may seem better, but in fact big-O notation only tells your how good the algorithm is in the terms of scaling, it never tells you how fast it performs (see this question also). And in your case scaling is not the issue, as your numNeighbours is limited to 20. In other words big-O notation describes how many ticks of algorithm is necessary for it to complete, but it doesn't limit the duration of a tick, it just says that the tick duration doesn't change when inputs change. And in terms of tick complexity your second algorithm surely wins.

What is the fastest way to compute k smallest elements?

I've came up with the next solution which I do believe allows branch prediction to do its job:
@Benchmark
public void testModified(Blackhole bh) {
    final double[] scores = sampleData;
    int[] candidates = new int[numberNeighbours];
    for (int i = 0; i < numberNeighbours; i++) {
        candidates[i] = i;
    }
    // sorting candidates so scores[candidates[0]] is the largest
    for (int i = 0; i < numberNeighbours; i++) {
        for (int j = i+1; j < numberNeighbours; j++) {
            if (scores[candidates[i]] < scores[candidates[j]]) {
                int temp = candidates[i];
                candidates[i] = candidates[j];
                candidates[j] = temp;
            }
        }
    }
    // processing other scores, while keeping candidates array sorted in the descending order
    for (int i = numberNeighbours; i < numberExamples; i++) {
        if (scores[i] > scores[candidates[0]]) {
            continue;
        }
        // moving all larger candidates to the left, to keep the array sorted
        int j; // here the branch prediction should kick-in
        for (j = 1; j < numberNeighbours && scores[i] < scores[candidates[j]]; j++) {
            candidates[j - 1] = candidates[j];
        }
        // inserting the new item
        candidates[j - 1] = i;
    }
    bh.consume(candidates);
}

Benchmark results (2x times faster than your current solution):
(10 neighbours) CounterBenchmark.testModified    thrpt    2  136492,151          ops/s
(20 neighbours) CounterBenchmark.testModified    thrpt    2  118395,598          ops/s

Others mentioned quickselect, but as one may expect, the complexity of that algorithm neglects its strong sides in your case:
@Benchmark
public void testQuickSelect(Blackhole bh) {
    final int[] candidates = new int[sampleData.length];
    for (int i = 0; i < candidates.length; i++) {
        candidates[i] = i;
    }
    final int[] resultIndices = new int[numberNeighbours];
    int neighboursToAdd = numberNeighbours;

    int left = 0;
    int right = candidates.length - 1;
    while (neighboursToAdd > 0) {
        int partitionIndex = partition(candidates, left, right);
        int smallerItemsPartitioned = partitionIndex - left;
        if (smallerItemsPartitioned <= neighboursToAdd) {
            while (left < partitionIndex) {
                resultIndices[numberNeighbours - neighboursToAdd--] = candidates[left++];
            }
        } else {
            right = partitionIndex - 1;
        }
    }
    bh.consume(resultIndices);
}

private int partition(int[] locations, int left, int right) {
    final int pivotIndex = ThreadLocalRandom.current().nextInt(left, right + 1);
    final double pivotValue = sampleData[locations[pivotIndex]];
    int storeIndex = left;
    for (int i = left; i <= right; i++) {
        if (sampleData[locations[i]] <= pivotValue) {
            final int temp = locations[storeIndex];
            locations[storeIndex] = locations[i];
            locations[i] = temp;

            storeIndex++;
        }
    }
    return storeIndex;
}

Benchmark results are pretty upsetting in this case:
CounterBenchmark.testQuickSelect  thrpt    2   11586,761          ops/s


text:
Q: The Microsoft Jet database engine cannot open the file ''.It is already opened exclusively by another user, or you need permission to view its data" i am using OLEDB server to read excel file in my ASP.NET MVC project. then i m getting error
"The Microsoft Jet database engine cannot open the file ''.It is already opened exclusively by another user, or you need permission to view its data". same code with different comnnection string of CSV file is work fine but For Excel connectionString i am getting this error. is there anyone know the solution for this please.
My code is:
public JsonResult ImportCSVFiles()
        {

            HttpPostedFileBase hpf = null;
            foreach (string file in Request.Files)
            {
                hpf = Request.Files[file] as HttpPostedFileBase;
            }
            string[] FileName;
            string filename = hpf.FileName;

            string DestinationPath = Server.MapPath("..") + "\\CSVFiles\\";

            if (!Directory.Exists(DestinationPath))
            {
                Directory.CreateDirectory(DestinationPath);

                if (System.IO.File.Exists(Server.MapPath("..") + "\\CSVFiles\\" + filename) == false)
                {
                    hpf.SaveAs(DestinationPath + filename);
                }
                else
                {
                    System.IO.File.Delete(Server.MapPath("..") + "\\CSVFiles\\" + filename);
                    hpf.SaveAs(DestinationPath + filename);
                }

            }
            else
            {

                if (System.IO.File.Exists(Server.MapPath("..") + "\\CSVFiles\\" + filename) == false)
                {
                    hpf.SaveAs(DestinationPath + filename);
                }
                else
                {
                    System.IO.File.Delete(Server.MapPath("..") + "\\CSVFiles\\" + filename);
                    hpf.SaveAs(DestinationPath + filename);
                }
            }

            bool isFirstRowHeader = true;
            string header = isFirstRowHeader ? "Yes" : "No";
            string path = "";
            string pathOnly = Path.GetDirectoryName(DestinationPath);
            string fileName = Path.GetFileName(DestinationPath + "\\" + filename);

            string sql = @"SELECT * FROM [" + fileName + "]";

            //using (OleDbConnection connection = new OleDbConnection(
            //          @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
            //          ";Extended Properties=\"Text;HDR=" + header + "\""))

            using (OleDbConnection connection = new OleDbConnection(
                  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
                  ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";"))

            using (OleDbCommand command = new OleDbCommand(sql, connection))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
            {
                DataTable dataTable = new DataTable();

                dataTable.Locale = CultureInfo.CurrentCulture;
                adapter.Fill(dataTable);
            }
}

commented connectionstring is for CSV file and CSV file works fine with same code.

A: I had the same problem with a program I was recently working on. My solution was to simply take out the extra bits from the connection string. I have no idea why it worked but since it worked for me, it might work for you. This is what your new connection string would look like:
using (OleDbConnection connection = new OleDbConnection(
              @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";"))

You actually might be able to keep the HDR=Yes bit just because I understand that you might need that to tell it there are headers and I don't think leaving it in would affect it.


text:
Q: Some keys not working properly in Lenovo G500 I use Lenovo G500 laptop which runs on Windows 8. It has a problem.

*

*Some keys that should be used along with Shift key is working not properly, its output is not correct. I will explain it. When I press 'Shift+2' it should show '@', but instead it is showing ". Also Shift+' should show ", but it is showing @. Also when Shift+3 gives me '£', instead of '#'. The back slash(not '/', its reverse slash) key is giving '#'. If want to put '\', I had to press Alt+.

Why this happens ? How can I fix this ?

A: Try updating the BIOS to see if it helps.
We have had similar problems at work with one of the notebooks (wrong reactions to the number keys), and after updating the BIOS they start working properly.
There might also be a hot-fix available on Lenovo's support page.

A: I have the same problem with my lenovo G500 Laptop. actually the keyboard and keys are functioning properly but,the problem is Printing mistake of letters on keys. they misplaced the keys @,",|,~,#,\, and the euro symbol. to fix this the only option is changing the keys.

A: In my case with Lenovo G500 , i set the keyboard language on UK English and works perfectly.


text:
Q: Visual Studio 2019 has errors in built-in libraries First time asking here, so please bear with me, or just let me know if I should do anything different.
I just installed a fresh version of Visual Studio 2019 and am trying to build a very basic C++ console application which includes Windows.h and iostream. Upon trying to build, I encounter over 100 build errors from the libraries that come with the IDE. Build output is shown below. Might anyone have a clue as to why the libraries that ship with VS2019 might cause so many build errors on their own?
Before you suggest Google and looking through other questions ashed here, I've searched in both places as well as Microsoft's knowledge base and have not been able to come across any relevant results. Thanks!
x32control.cpp:
#include "common.h"

int main ()
{
    return errAndDie ("\nTesting errAndDie.\n\n");
}

common.cpp:
#include <iostream>
#include <winddi.h>

int errAndDie (const char* errorMessage) {
    std::cout << errorMessage;
    return -1;

common.h:
#ifndef COMMON_H
#define COMMON_H

#include <iostream>
#include <Windows.h>

int errAndDie (const char *errorMessage);

#endif

Errors:
1>common.cpp
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(90,22): error C3646: 'Data1': unknown override specifier
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(90,22): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(91,22): error C3646: 'Data2': unknown override specifier
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(91,22): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(92,22): error C3646: 'Data3': unknown override specifier
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(92,22): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(93,22): error C3646: 'Data4': unknown override specifier
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(93,22): error C2143: syntax error: missing ',' before '['
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(93,25): error C2143: syntax error: missing ')' before ';'
1>D:\Windows Kits\10\Include\10.0.18362.0\um\winddi.h(93,25): error C2238: unexpected token(s) preceding ';'
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddrawint.h(32,1): error C2146: syntax error: missing ';' before identifier 'GUID_MiscellaneousCallbacks'
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddrawint.h(32,122): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddrawint.h(33,1): error C2146: syntax error: missing ';' before identifier 'GUID_Miscellaneous2Callbacks'
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddrawint.h(33,124): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddrawint.h(34,1): error C2146: syntax error: missing ';' before identifier 'GUID_VideoPortCallbacks'
...
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddraw.h(296,44): error C3646: 'lpDDSZBufferSrc': unknown override specifier
1>D:\Windows Kits\10\Include\10.0.18362.0\um\ddraw.h(296,44): fatal error C1003: error count exceeds 100; stopping compilation
1>httpserver.cpp
1>x32control.cpp
1>Generating Code...
1>Done building project "x32control.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

A: I have found the issue. Including winddi.h in common.cpp was the issue. I'm not entirely sure how that got in there, as I do not recall ever typing that and I don't copy/paste often. My apologies for not noticing this ahead of posting. Sometimes new contexts make it easier to see these things.


text:
Q: Creating an executable file at Visual Studio Code I am relatively new in programming using the C-language. So to lay it all out, I am still kind of clueless of what is happening. Now, may I ask why I can't seem to create an exe file and run the code?
Actually, the first time I tried executing it, it worked. However, to make sure that it is working, I repeated it and then it didn't work anymore.
To make things clearer:

*

*I use Mac

*Mac OS Big Sur

*In this particular case, gcc is the compiler

*I also tried using Code::Blocks also prior to this; however, I have similar issues -- after I built and ran my first "hello world" program, it didn't run the same program anymore after it. I also tried reinstalling it, but it still has the same issues.

I'm really frustrated that this is happening because I cannot move on to the next lessons in my class. :(
Thank you very much! I hope someone would help a newbie here. :))

A: Gcc by default names executables a.out. So you can check if that file has been created by running ls a.out and looking through the results.
If it has been made, you can run it from the command line with ./a.out.
If you want to name the executables something else, then when calling gcc, add the flag -o followed by the name you want. E.g. if you want filename.c to compile to filename.exe, then you would write gcc -o filename.exe filename.c. Then you can run it from the command line with ./filename.exe. I think if you give it the .exe file extension you should also be able to run it by clicking it in the Windows file explorer.


text:
Q: How to perform own assertions with coded UI testing I'm working with the visual studio 2010 codedUI tests.
I want to be able to perform a little more than i can at the moment.
e.g. I can can Assert if a particular field "AreEqual" to or "Contains" etc, but i want to do more.
eg, i want to check if the field contains a numerical value within it.
I edited the UIMap.Designer.cs and was able to achieve what i wanted.
The only problem is is that this file gets overwritten when new test are added.
so my question is how can i "fiddle" with fields/stings in the UI and implement my own assertions on them?
Thanks

A: Use the partial class created (UIMap.cs) to add your custom code. This file doesn't get blown away and has full access to the internals of the UIMap (since it's part of it).

A: You can get it done dude, but be careful by keeping back up.
Open uitest file :

*

*Go to test marker node that contains the relevant assertion,

*Delete the method.

*Save and find the stuff you expect

Its beeen working great for me but one two occasions I was dumbfound to face many issues with my acriipt running. So have back up and  test this out.

A: I was told that the solution in "Coded UI" was to create your own libraries and then twitch your new test cases accordingly.
Haven't tried it, though.


text:
Q: Mavericks Disc Image I want to make a USB bootable to downgrade from Yosemite to Mavericks. I don't have Mavericks in my recent purchases in the App Store because my Mac shipped with it. Recovery mode just installs Yosemite. Does anyone have a link to where I can download the OS X Mavericks installer?

A: In order to reset your Mac to your shipped OS you just need to boot it from Recovery Mode, but install from the Internet. It's probably installing Yosemite because you might be restoring from a backup or your possibly doing a Recovery from the drive (which in this case would be the current OS recovery: i.e., Yosemite)
Here is the difference between the two:

*

*If you use the Recovery System stored on your startup drive to reinstall OS X, it installs the most recent version of OS X previously installed on this computer.

*If you use Internet Recovery to reinstall OS X, it installs the version of OS X that originally came with your computer. After installation is finished, use the Mac App Store to install related updates or later versions of OS X that you have previously purchased.

See the how-to-guide and additional information reguarding Recovery HERE
NOTE it states in the docs that it automatically detects when the Recovery System on the startup drive isn't available, however you can manually elect this in the Recovery menu


text:
Q: geocoder.getLatLng() method not showing all the addresses on google map? I have latitude and longitude values in the database columns(More that 20), so i am just grabing those values and passing them to geocoder.getLatLng() method to display them as markers. But this method not pretty fast, I kept this method inside a loop to run through all the values from database, But not all the addresses are showing up everytime I refresh the page its missing some addresses.Here is my code, please give me some suggestions and tell how to set the time out.
        script += " var location = \"\"+ latitude +\", \"+ longitude +\"\";\n";

        script += " geocoder.getLatLng( \n";
        script += " location,function(point) \n";
        script += " {if (point) { \n";
        //script += "       alert(point);\n";
        script += "     var icon = new GIcon(baseIcon);\n";
        script += "     icon.image = \"_gfx/gmap/marker\" + (iconNum) + \".png\";\n";
        script += "     var LocImage = new Image();\n";
        script += "     LocImage.src =\"Modules/ShowImage.aspx?imageid=\"+ ImageID +\"\";\n";
        script += "     var marker = new GMarker(point, icon);\n";
        script += "     map.addOverlay(marker); \n";
        script += "     GEvent.addListener(marker, \"click\", function() {\n";
        script += "         marker.openInfoWindowHtml(\"
\" + name + \"
\" +((ImageID!= \"0\")?\"\":\"\")+ \"
\" + displayAddress + \"
\" +((PhoneNum != \"\")?\"Phone:\"+PhoneNum+\"\":\"\")+ \"
\" + AllAmenities + \"Capacity:\" + Capacities + \"
\");\n";
        script += " })\n";
        script += "     return marker;\n";
        script += " }\n";


text:
Q: How can I get data from a Map on Firebase where the values are 'true'? I have this Map likes there I use to save the information of people who liked a post.
I save the field with the idof each user, and I would like to access this field but only the documents that are true and use the id to get the users profile. How can I access the Map and get the ids?

A: As I understand, you want to access the list of user ids that are in your likes map. In that case, you can do this:
// Get the post
final DocumentSnapshot post = await Firestore
    .instance
    .collection('posts')
    .document(postId).get(); // Here postId is the id of the post you are accessing

// You can then get the ids list
final ids = post.data['likes'];

// Get the list of ids that has value = true
final userIds = ids.keys.map((e) => ids[e] == true).toList();

You can store likes as an array instead of Map for convenient data handling, since this likes field only store those that liked the post according to the name.