text:
Q: Fatal error: Constant expression contains invalid operations При попытке присвоить переменной класс получаю ошибку. Я только начинаю прошариваться в ООП, так что не знаю, что делаю не так
class SendMessage
{
    public $chatid = '';
    public $message ='';

    //Fatal error: Constant expression contains invalid operations in /file on line 7
    public $connection = new MakeConnection();

    public function SendTextMessage() {
        $connection->method = "sendMessage?chat_id=".$this->chatid.'&text='.$this->message;
        return $connection->ReturnConnection();
    }
}

A: Написано же, что нельзя так делать public $connection = new MakeConnection();
Задавай значение в конструкторе.


text:
Q: Keep autolayout contraints after changing superview in the storyboard I have a UIView in the storyboard where all the constraints are defined. Now I have to change it so that all the subviews are inside a new scroll view. I drag a scroll view into the view, adjust the size and then add all the subviews into the scroll view. All the autolayout constraints are now out of place and the best solution I find is to delete the constraints and create them again, but this is very time consuming. Is there a better way to do this?

A: Unfortunately, there is no easy way to transfer the constraints. You can take a look at this article that shows how to edit your storyboard in a text editor.
One thing that can at least help a little bit is the "Embed In" functionality. This will wrap a container around your selected child views and at least save you the time of repositioning everything.
Editor > Embed In > Scroll View

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing sqlite data to chrome browser I have got a .sqlite file which has table definition and data. I want to store this data to chrom broswer and query against it. I tried query it against the physical file but it does not seem to work. Any ideas?

A: You have to use JavaScript and a WebSQL database. See: http://dev.w3.org/html5/webdatabase/
But importing your file is not that easy because with WebSQL you can't read an sqlite file but WebSql is the only way for storing information via SQL in Chrome.


text:
Q: CPU soft cores on FPGA I need advice here.
One of my mid term hobby projects is to build an instruction set emulator of popular ISAs (e.g. ARM7) on a FPGA device. A lot of people have done this before.
My requirements are specific.  I am looking for a development platform with SoC reference project and onboard peripheral support. Idea is to focus only on the CPU while the rest of the stuff comes from a reference project. It should be possible to compile and download an application in C into onboard volatile memory such as SDRAM have the soft core execute it.
What could be a possible development platform?

A: You can look at the Altera DE2 boards, make sure they have enough memory for your purposes though.


text:
Q: Need reference to an assertion re: Riemann I have been exploring the patterns of the greatest divisors $\leq$ to the square root $n$ for sequences of size $n$. Just for grins, I used $\textit{Mathematica}$ to produce this ListLinePlot:

When I saw how symmetrical it was, I had to look up the sequences: OEIS A003418
The third sentence in the comments states that this sequence relates to this assertion regarding Riemann: for $n > 2$
$$|\log (\text{lcm}(n))-n |<\sqrt{n} \log ^2(n)$$
Where could I find a book or paper that describes that assertion?

A: We have
$$ \log\text{lcm}(1,\dots,n)=\sum_p\log p\left[\frac{\log n}{\log p}\right] =\sum_p \log p\sum_{k\log p\leq \log n} 1 = \sum_{p^k\leq n}\log p.$$
The right hand side is the summatory function of the von Mangoldt function, which is known as the second Chebyshev function:
$$ \psi(n):=\sum_{m\leq n}\Lambda(m). $$
That is, the bound you are asking about is
$$ |\psi(n)-n|<\sqrt{n}\log^2 n.$$
The fact that the Riemann Hypothesis implies this bound for $n>73$ (hence probably also for $n>2$) follows from this paper. The other direction, that such a bound with any constant in front of $\sqrt{n}\log ^2 n$ implies the Riemann Hypothesis, is more classical and can be found in many textbooks (see e.g. the bottom of p.463 in Montgomery-Vaughan: Multiplicative Number Theory I).


text:
Q: How to Make a Splash Screen I have a program which should has splash screen on JPanel, after button click should show another JPanel (object of the class) and draw shapes. I tried remove splash JPanel and after that add JPanel for drawing but it doeesn't work. How can I fix it? Two JLabel should be in the center of screen and it should be on 2 lines.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JComponent;

/**
 *
 * @author Taras
 */
public class MyComponent extends JComponent {
    int i;
    Color randColor;

    public MyComponent()
    {
        this.i = i;
        addMouseListener(new MouseHandler());
    }

    private ArrayList<Rectangle2D> arrOfRect=new ArrayList<>();
    private ArrayList<Ellipse2D> arrOfEllipse=new ArrayList<>();
   // private ArrayList<Color> randColor = new ArrayList<>();
    Random rand = new Random();
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    for (Rectangle2D r : arrOfRect) {
        g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
        g2.draw(r);

    }
    for (Ellipse2D e : arrOfEllipse) {
        g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
        g2.draw(e);
    }

}
    public void add(Point2D p)
    {
        double x=p.getX();
        double y=p.getY();
        if (Pole.i == 1){
                Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,100);
                //randColor = new Color(randRed(), randGreen(), randBlue());

                arrOfEllipse.add(ellipse);
            }
        if (Pole.i == 2){
        Rectangle2D rectangls=new Rectangle2D.Double(x, y, 100, 100);
        arrOfRect.add(rectangls);

        }
        if (Pole.i == 3){
        Rectangle2D rectangls=new Rectangle2D.Double(x, y, 150, 100);
        arrOfRect.add(rectangls);

        }
        if (Pole.i == 4){
                Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,50);
                arrOfEllipse.add(ellipse);
            }
    }
    private class MouseHandler extends MouseAdapter {
        public void mousePressed(MouseEvent event)
        {
            add(event.getPoint());
            //Color rColor = new Color(randRed(), randGreen(), randBlue());
            //randColor.add(rColor);
            repaint();

        }

    }

    private int randRed() {
        int red;
        Random randomNumber = new Random();
        red = randomNumber.nextInt(255);
        return red;
    }

    private int randGreen() {
        int green;
        Random randomNumber = new Random();
        green = randomNumber.nextInt(255);
        return green;
    }

    private int randBlue() {
        int blue;
        Random randomNumber = new Random();
        blue = randomNumber.nextInt(255);
        return blue;
    }
}

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import org.omg.CosNaming.NameComponent;

public class Pole extends JFrame {

    public static int i;
public static JPanel nameContainer = new JPanel(new GridLayout(2, 1));
public static JFrame frame= new JFrame("Shape Stamper!");

    public static void main(String[] args) {

   JPanel container;

     JButton circle = new JButton("Circle");
     JButton square = new JButton("Square");
      JButton rectangle = new JButton("Rectangle");
      JButton oval = new JButton("Oval");
      JLabel programName = new JLabel("Shape Stamper!");
      JLabel programmerName = new JLabel("Progrramed by: ");

     Font font = new Font("Serif", Font.BOLD, 32);
     programName.setFont(font);
     font = new Font("Serif", Font.ITALIC, 16);
     programmerName.setFont(font);

    programName.setHorizontalAlignment(JLabel.CENTER);

    programmerName.setHorizontalAlignment(JLabel.CENTER);
    //programmerName.setVerticalAlignment(JLabel.CENTER);
    // nameContainer.setLayout(new BorderLayout());
     nameContainer.add(programName);
     nameContainer.add(programmerName);
     //nameContainer.setLayout(new BoxLayout(nameContainer, BoxLayout.X_AXIS));
        container = new JPanel(new GridLayout(1, 4));
        container.add(circle);
        container.add(square);
        container.add(rectangle);
        container.add(oval);

     circle.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                i = 1;
                frame.remove(nameContainer);
                frame.repaint();
                System.out.println(i);
            }
        });

     square.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                i = 2;
            }
        });

     rectangle.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                i = 3;
            }
        });

     oval.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                i = 4;
            }
        });

     MyComponent shape = new MyComponent();
      frame.setSize(500, 500);

      frame.add(shape, BorderLayout.CENTER);

        frame.add(container, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
}
}

A: Here's an example of making a splash screen using an image.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

public class CircleSplashScreen {

    public CircleSplashScreen() {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new ImagePanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setBackground(new Color(0, 0, 0, 0));
        frame.setVisible(true);
    }

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

    @SuppressWarnings("serial")
    public class ImagePanel extends JPanel {

        BufferedImage img;

        public ImagePanel() {
            setOpaque(false);
            setLayout(new GridBagLayout());
            try {
                img = ImageIO.read(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
            } catch (IOException ex) {
                Logger.getLogger(CircleSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }
    }
}


text:
Q: Couchdb 2 run on openstack I know there are implementations of couchdb 1.6 on openstack/openshift.  But im looking for latest v2.0
If there are non, what about cloud foundry, is there an implementation for couchdb2 on it?
if no premade implementations, can someone point me to some good instructions on how to do it.
Mike

A: You can use couchdb in several ways:

*

*as CF service

*as external installation

*as application

To use it as a service you need to have a Service Broker and admin access to the Cloud Foundry installation you want to use. Admin access is necessary to add the service to CF and expose it to every CF user (or to restrict access). You can go the usual CF way and use BOSH. A good starting point could be to improve the 1.5 release or the community release.
Since you are talking for openstack I guess you already have infrastructure access. You can run CouchDB on openstack and use it as user-provided service. You'll need to open access from CF to the CouchDB network and Couch won't be visible in the CF marketplace.
Since Couch uses HTTP/HTTPS you can push it as a regular application using Docker image and use it from other applications. This can be the fastest way, but should be used for development/testing only.


text:
Q: Replace elements of tuples from list of tuples - Python I want to write a python program to replace last value of tuples in a list with a certain number (lets say 100).
my list: [(10,20,30),(40,50,60),(70,80,90)]
expected output: [(10,20,100),(40,50,100),(70,80,100)]

A: Since tuples are immutable, you will have to reassemble new ones:
lst = [(10,20,30),(40,50,60),(70,80,90)]

new_lst = [tpl[:-1] + (100,) for tpl in lst]
# [(10, 20, 100), (40, 50, 100), (70, 80, 100)]

This uses a list comprehension over the new tuples, which are concatenations of the appropriate slices with a singleton tuple ((100,)). Note that the comma is important.

A: >>> lst = [(10,20,30), (40,50,60), (70,80,90)]
>>> [(*t[:-1], 100) for t in lst]
[(10, 20, 100), (40, 50, 100), (70, 80, 100)]

similar to schwobaseggl's answer, but rather than appending to a tuple with + operator, I prefer to unpack the elements desired. The benefit of doing so is readability.
explanation
for every tuple t in the list lst, we apply (*t[:-1], 100).
In python, negative indices gets you the element in a list/tuple counting backwards, so [-1] gets you the last item. [a:b] gets you the ath item to the b-1th item. So t[:-1] gets you items in t upto the one before the last one.
* operator unpacks the slice. and puts them in the new tuple alongside with 100. So it is equivalent to (.., .., .., .., 100) and the ".." represents all the items unpacked, which in this case is the items in tuple t excluding the last item.
Hope you found this helpful and maybe earned something :)

A: You could use list comprehension in this case.
But one problem you can come across when trying this is modifying the tuple. So a workaround would be to use list() in order to convert the tuple to a list to make it mutable.
Then we need to take all the elements before the last and concatenate that with 100.
Note that list(tup)+100 won't work because the list can only concrete with another list.
org = [(10,20,30),(40,50,60),(70,80,90)]
new = [tuple(list(tup[:-1])+[100]) for tup in org]
print(new)

output
[(10, 20, 100), (40, 50, 100), (70, 80, 100)]

A: Please refer this case earlier :
Python: Change tuple in a list of tuples
OR You can go through this link for better understanding:
Replace tuple according to Nth tuple element


text:
Q: How can I assign a function to a variable without executing it? When I try to assign a map key to a function it executes the function. How can I do this without executing the function?
var myslice []int
myslice = append(myslice, 1)

func RemoveIndex(s []string, index int) []string {
    return append(s[:index], s[index+1:]...)
}

a["removeIndex"] = removeIndex(myslice, 0)

A: Just assign the function to the map[string]func([]string,int)[]string's key
func RemoveIndex(s []string, index int) []string {
    return append(s[:index], s[index+1:]...)
}

a["removeIndex"] = RemoveIndex

rifn := a["removeIndex"]

rifn(myslice, 0)


text:
Q: How to transpose an 2x2 array? I have an array in the form:
var a1 = [
   ['AA', 1],
   ['AA', 2],
   ['AA', 3],
   ['BB', 7],
   ['BB', 8],
   ['BB', 9]
];

I want to transform it into:
output = [
           ['AA':1,2,3],
           ['BB':7,8,9]
]

I need to transform it this way so I can put my JSON formatted data that comes from SQL into a highcharts graph that seems to need the array series as follows
https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/streamgraph/

A: Try something like this

var a1 = [
   ['AA', 1],
   ['AA', 2],
   ['AA', 3],
   ['BB', 7],
   ['BB', 8],
   ['BB', 9]
];

function generateObj(array) {
  const obj = {}
  array.forEach(entry => {
    obj[entry[0]] = obj[entry[0]] || []
    obj[entry[0]].push(entry[1])
  })
  return obj
}

console.log(generateObj(a1))


text:
Q: Simple example of use of __setstate__ and __getstate__ I don't know what the __setstate__ and  __getstate__ methods do, so help me with a simple example.

A: Minimal example
Whatever comes out of getstate, goes into setstate. It does not need to be a dict.
Whatever comes out of getstate must be pickeable, e.g. made up of basic built-ins like int, str, list.
class C(object):
    def __init__(self, i):
        self.i = i
    def __getstate__(self):
        return self.i
    def __setstate__(self, i):
        self.i = i
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

Default __setstate__
The default __setstate__ takes a dict.
self.__dict__ is a good choice as in https://stackoverflow.com/a/1939384/895245 , but we can construct one ourselves to better see what is going on:
class C(object):
    def __init__(self, i):
        self.i = i
    def __getstate__(self):
        return {'i': self.i}
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

Default __getstate__
Analogous to __setstate__.
class C(object):
    def __init__(self, i):
        self.i = i
    def __setstate__(self, d):
        self.i = d['i']
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

__slots__ objects don't have __dict__
If the object has __slots__, then it does not have __dict__
If you are going to implement both get and setstate, the default-ish way is:
class C(object):
    __slots__ = 'i'
    def __init__(self, i):
        self.i = i
    def __getsate__(self):
        return { slot: getattr(self, slot) for slot in self.__slots__ }
    def __setsate__(self, d):
        for slot in d:
            setattr(self, slot, d[slot])
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

__slots__ default get and set expects a tuple
If you want to reuse the default __getstate__ or __setstate__, you will have to pass tuples around as:
class C(object):
    __slots__ = 'i'
    def __init__(self, i):
        self.i = i
    def __getsate__(self):
        return (None, { slot: getattr(self, slot) for slot in self.__slots__ })
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

I'm not sure what this is for.
Inheritance
First see that pickling works by default:
class C(object):
    def __init__(self, i):
        self.i = i
class D(C):
    def __init__(self, i, j):
        super(D, self).__init__(i)
        self.j = j
d = pickle.loads(pickle.dumps(D(1, 2), -1))
assert d.i == 1
assert d.j == 2

Inheritance custom __getstate__
Without __slots__ it is easy, since the __dict__ for D contains the __dict__ for C, so we don't need to touch C at all:
class C(object):
    def __init__(self, i):
        self.i = i
class D(C):
    def __init__(self, i, j):
        super(D, self).__init__(i)
        self.j = j
    def __getstate__(self):
        return self.__dict__
    def __setstate__(self, d):
        self.__dict__ = d
d = pickle.loads(pickle.dumps(D(1, 2), -1))
assert d.i == 1
assert d.j == 2

Inheritance and __slots__
With __slots__, we need to forward to the base class, and can pass tuples around:
class C(object):
    __slots__ = 'i'
    def __init__(self, i):
        self.i = i
    def __getstate__(self):
        return { slot: getattr(self, slot) for slot in C.__slots__ }
    def __setstate__(self, d):
        for slot in d:
            setattr(self, slot, d[slot])

class D(C):
    __slots__ = 'j'
    def __init__(self, i, j):
        super(D, self).__init__(i)
        self.j = j
    def __getstate__(self):
        return (
            C.__getstate__(self),
            { slot: getattr(self, slot) for slot in self.__slots__ }
        )
    def __setstate__(self, ds):
        C.__setstate__(self, ds[0])
        d = ds[1]
        for slot in d:
            setattr(self, slot, d[slot])

d = pickle.loads(pickle.dumps(D(1, 2), -1))
assert d.i == 1
assert d.j == 2

Unfortunately it is not possible to reuse the default __getstate__ and __setstate__ of the base: https://groups.google.com/forum/#!topic/python-ideas/QkvOwa1-pHQ we are forced to define them.
Tested on Python 2.7.12. GitHub upstream.

A: A clarification to @BrainCore's answer. In practice, you probably won't want to modify self inside __getstate__. Instead construct a new object that will get pickled, leaving the original unchanged for further use. Here's what that would look like:
import pickle

class Foo:
    def __init__(self, x:int=2, y:int=3):
        self.x = x
        self.y = y
        self.z = x*y

    def __getstate__(self):
        # Create a copy of __dict__ to modify values and return;
        # you could also construct a new dict (or other object) manually
        out = self.__dict__.copy()
        out["x"] *= 3
        out["y"] *= 10
        # You can remove attributes, but note they will not get set with
        # some default value in __setstate__ automatically; you would need
        # to write a custom __setstate__ method yourself; this might be
        # useful if you have unpicklable objects that need removing, or perhaps
        # an external resource that can be reloaded in __setstate__ instead of
        # pickling inside the stream
        del out["z"]
        return out

    # The default __setstate__ will update Foo's __dict__;
    # so no need for a custom implementation here if __getstate__ returns a dict;
    # Be aware that __init__ is not called by default; Foo.__new__ gets called,
    # and the empty object is modified by __setstate__

f = Foo()
f_str = pickle.dumps(f)
f2 = pickle.loads(f_str)

print("Pre-pickle:", f.x, f.y, hasattr(f,"z"))
print("Post-pickle:", f2.x, f2.y, hasattr(f2,"z"))

A: These methods are used for controlling how objects are pickled and unpickled by the pickle module.  This is usually handled automatically, so unless you need to override how a class is pickled or unpickled you shouldn't need to worry about it.

A: Here's a very simple example for Python that should supplement the pickle docs.
class Foo(object):
  def __init__(self, val=2):
     self.val = val
  def __getstate__(self):
     print("I'm being pickled")
     self.val *= 2
     return self.__dict__
  def __setstate__(self, d):
     print("I'm being unpickled with these values: " + repr(d))
     self.__dict__ = d
     self.val *= 3

import pickle
f = Foo()
f_data = pickle.dumps(f)
f_new = pickle.loads(f_data)

Output:
I'm being pickled
I'm being unpickled with these values: {'val': 4}


text:
Q: Python continue and break usage I need to solve the following problem and I assume I have to use continue and break logic.

*

*I have to create an empty to do list and iterate over the dictionary of tasks. I need to add tasks that contain the substring "organize" and once the length of the to do list reaches 2 tasks I break the loop. *

tasks = {
    0 : ['Reorganize the cabinet'],
    1 : ['Give the dog a bath', 'Create a twitter thread'],
    2 : ['Learn python dictionary'],
    3 : ['Take a walk'],
    4 : ['Go grocery shopping'],
    5 : ['Update Facebook'],
    6 : ['Respond to emails'],
    7 : ['Walk the dog']
}

I could solve the second part of adding the tasks that contain the substring "organize"  and could iterate through the length of tasks to filter tasks that are not more than 2. Yet, I can't find the way how to combine two conditions into one.

A: Put an if statement in the loop that checks the length of the to do list, and breaks out of the loop when it reaches 2.
todo_list = []
for task in tasks.values():
    if any('organize' in item for item in task):
        todo_list.append(task)
    if len(todo_list) == 2:
        break

A: does this do the job:
to_do_list = []
for value in tasks.values():
    to_do_list.append([val for val in value if 'organize' in val])
    if len(to_do_list) == 2:
        break

If you want a flattened list of items, replace to_do_list.append with to_do_list.extend

A: This will work :
to_do_list = []

for task in tasks.values():
    for i in task :
        if 'organize' in i:
            to_do_list.append(i)
    if len(to_do_list) == 2:
        break


text:
Q: PHP/MySQL small-scale fuzzy search I'm looking to implement fuzzy search for a small PHP/MySQL application. Specifically, I have a database with about 2400 records (records added at a rate of about 600 per year, so it's a small database). The three fields of interest are street address, last name and date. I want to be able to search by one of those fields, and essentially have tolerance for spelling/character errors. i.e., an address of "123 Main Street" should also match "123 Main St", "123 Main St.", "123 Mian St", "123 Man St", "132 Main St", etc. and likewise for name and date.
The main issues I have with answers to other similar questions:

*

*It's impossible to define synonyms for every possible incorrect spelling, forget doing so for dates and names.

*Lucene, etc. seems very heavy-weight for such a limited search data set (call it a maximum of 5,000 records, 3 fields per record).

*Just doing something with wildcards doesn't seem logical with all of the possible spelling errors.

Any suggestions? I know it isn't going to be possible to do natively with MySQL, but since the data set is so limited, I'd like to keep it relatively simple... perhaps a PHP class that gets all of the records from the DB, uses some sort of comparison algorithm, and returns the IDs of the similar records?
Thanks,
Jason

A: Razzie's answer (or using Damerau–Levenshtein) ranks a list of candidates matches according to their closeness to the search key. (Take care: if the key is "12 Main St" then "13 Main St" has the same typing distance as "12 Moin St" but you might want to rank it low or even exclude it, as with 11 and 22 Main St etc.)
But how do you select a list of candidates of a manageable size to rank?
One way is to compute the metaphone value (or values, using double-metaphone) for each word in the strings your going to search. Save each of these metaphones in another table with the id of the row containing the original string. You can then search these metaphone values quickly with LIKE 'key%' where key is the metaphone of a word from the search text.
Check out the suggested answer on this thread. It's quite neat and should work nicely for DBs that aren't huge.

A: If it is a very small database, you could load all the data at once and use an algorithm like Jaro-Winkler for your search. They have an implementation in PHP, which you can find here.
Imho it works really well. Take a look at an example implementation here. I know that that search uses the same algorithm, and it can find 'Nintedno' very well. It also sorts the results for you, based on which result best matches your query.


text:
Q: SQL "LIKE" If empty returns all rows Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"

Thank you all

A: If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
    $sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
    $sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}

A: You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"

Explanation:

*

*First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'

*Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.


text:
Q: Chef encountered with unable to create a node While I am running the "chef-client" of my json file. I am unable to obtain the client.pem file. Th chefserver instance is being running in google cloud platform of OS platform "RHEL7". So, could you please help me out? 1

A: knife bootstrap, is a part of the node bootstrap (see step 2):

The knife bootstrap command will install the chef-client executable (if necessary), generate keys, and register the node with the Chef server.

the generate keys is the generation of client.pem, which is used to authenticate the node on the chef-server. thus, it appears that the bootstrap did not complete successfully or some changes were made to the node client.rb that reference the client.pem.

A: Here I am attaching the image of "client.rb" file. So, please have a look.enter image description here


text:
Q: VBScript file or folder selection I have a small hta file with few vbs codes. It selects folder or file then make a copy to a fixed location.

<Title>File Copy </Title>

<HTA:APPLICATION ID=""
   applicationName=""
   version="1.1"
    BORDER="thin"
    BORDERSTYLE="static"
    CAPTION="Yes"
    CONTEXTMENU="no"
    ICON="C:\icon\32x32.ico"
    INNERBORDER="no"
    MAXIMIZEBUTTON="no"
    MINIMIZEBUTTON="no"
    NAVIGATABLE="no"
    SCROLL="no"
    SCROLLFLAT="no"
    SELECTION="no"
    SHOWINTASKBAR="yes"
    SINGLEINSTANCE="yes"
    SYSMENU="yes"
    WINDOWSTATE="normal"
>

Please select the file.

<form name="Copy_To_PC">
<input type = "text" name = "txtFile" size="100" />
<input type = "button" value = "File Source" Name="BrowseSource">
<input type="button" value="Copy and Paste" name="RunScripts">
</form>

I have problems with selecting items (folder or file) when I click the first button.

*

*It picks up folder well but when selecting files, I got "unspecified error on line 60", please help me to troubleshoot. I want the file browser window like the way it is now with OK button on it, not a "open" button, so I can select both folder or file.

*Also the file browser does not start up from the location I setup.
How to fix it?

A: How to select folder or file in the same window? By MSDN, The Shell.BrowseForFolder method creates a dialog box that enables the user to select a folder and then returns the selected folder's Folder object.
Thus, for browse for a file we need to use another method. There exists the native <input ...> tag with type="file" attribute.  However, using it brings more cons than pros (see 2nd solution below).
In next solution, the Browse for File is achieved by using the HtmlDlgHelper object - an obscure and poorly documented object that is nevertheless available on all Windows systems... In comparison with <input ...> tag mentioned above, this solution offers to define both initial location and file type masking.

<Title>File/Folder Copy B</Title>

<HTA:APPLICATION
    ID=""
    APPLICATIONNAME="28632270ym"
    SCROLL="no"
    SINGLEINSTANCE="yes"
    WINDOWSTATE="normal"
>

<OBJECT id=Dlg classid="CLSID:3050F4E1-98B5-11CF-BB82-00AA00BDCE0B"
    width=0 height=0>
</OBJECT>
<FORM  name="Copy_To_PC">

Please select a file or folder.

<input style="width:600px;" type="text" id="txtfile" name="txtfile" />

<input type="button" value="Browse for File..."  id="BrForFile">
  or
<input type="button" value="Browse for Folder..." onClick=BrForFolder()>

Action
<input type="button" value="Undefined" id="OKbuton" onClick=DoFileOK()>

Quit:
<input type="button" value="All done" onClick=self.window.close()>
</FORM>

2nd solution:

<Title>File/Folder Copy A</Title>

<HTA:APPLICATION
    ID=""
    APPLICATIONNAME="28632270my"
    SCROLL="no"
    SINGLEINSTANCE="yes"
    WINDOWSTATE="normal"
>

<form  name="Copy_To_PC">

Please select a file or folder.

<input style="width:600px;" type="text" id="txtfile" name="txtfile" />
<input style="width:0px;"   type="file" id="fn_file" name="fn_file"
    accept=sFilter onChange=BrForFile() onBlur=BrForFile()>
 or
<input type="button" value="...for Folder..." onClick=BrForFolder()>

Action
<input type="button" value="Undefined" id="OKbuton" onClick=DoFileOK()>

Quit:
<input type="button" value="All done" onClick=self.window.close()>
</form>

A: Here is an example of setting the start directory and the selection of files.
Const GeneratedItemFlag = &h4000

dim shellApp
dim folderBrowseDialog
dim filePath
set shellApp = CreateObject("Shell.Application")

set folderBrowseDialog = shellApp.BrowseForFolder(0,"Select the file", GeneratedItemFlag, "c:\")

if folderBrowseDialog is nothing then
    msgbox "No file was selected.  This will now terminate."
    Wscript.Quit
else
    filePath= folderBrowseDialog.self.path
end if

A: There is actually an error in the HTA portion of the first code example that will cause some problems down the road. The tag says NAVIGATABLE="no". It should be NAVIGABLE="no". You need to lose the AT.

A:

<HTA:APPLICATION SCROLL="no" SYSMENU="no" >

<TITLE>Your Project Folder </TITLE>

<form name="myForm" onsubmit="return validateForm()">
pathtostore: <input type="text" name="pname" value="c:\program files">
<input type="button" onclick="selectPath()" value="Browse">

<input type="submit" value="ok">
</form>


text:
Q: Fluent NHibernate Mapping - Saving Child object I'm having a problem with Fluent NHibernate mappings, I think, and can't quite get past how I should be setting the mapping to avoid an issue.
I have a business object (literally, a "business"), and a review object.  Each Business can have multiple reviews that are created on a page in the UI.  The business is a property of the Review, as follows:
public class Business
{
    public virtual int BusinessId {get;set;}
    public virtual DateTime LastModified {get;set;}
    public virtual IList<Review> Reviews {get;set;}

    [... more removed for brevity ...]

}

public class Review
{
    public virtual int ReviewId {get;set;}
    public virtual string ReviewText {get;set;}
    public virtual Business Business {get;set;}

    [... more removed for brevity ...]

}

My mappings are as follows:
public class ReviewMap : ClassMap<Review>
{
    public ReviewMap()
    {
        WithTable("Reviews");
        Id(x => x.ReviewId).TheColumnNameIs("ReviewId").GeneratedBy.Identity();

        References(x => x.Business).TheColumnNameIs("BusinessId");

        Map(x => x.ReviewText);

       [... and so on...]
}

public class BusinessMap : ClassMap<Business>
{
    public BusinessMap()
    {
        WithTable("Businesses");

        Id(x => x.BusinessId).TheColumnNameIs("BusinessId").GeneratedBy.Identity();

        Map(x => x.Name).TheColumnNameIs("BusinessName");
        Map(x => x.LastModified, "LastModifiedOn");

        HasMany<Review>(x => x.Reviews)
            .Inverse()
            .LazyLoad();

        [... more removed for brevity ...]

    }
}

The repository code is
public void Save(T entity)
    {
        using (ISession session = GetSession())
        using (ITransaction tx = session.BeginTransaction())
        {
            session.SaveOrUpdate(entity);
            tx.Commit();
        }
    }

In the code, I assign the properties to the Review object, and call the Repository's Save method.
The problem is that since I'm not updating the Business per se, I don't expect it to get saved--all I want is the review saved.  But the code tries to save the Business as well, and I get an excption, as I haven't set the "LastModified" property--nor do I want to, as I'm saving the REVIEW, not the business.
How should I be setting up the mapping to let this happen?

A: The issue could be coming for a forign key requirement between the Business and Review.  The business (parent) usually needs to be saved before the review (child) can be.
Could you include the mapping of your Business object if this doesn't help?

A: Ok, so the problem was this: the Business's LastModified property wasn't actually set in the actual business object, as the database allowed NULL for this property.
What that meant was that when I tried to save the review, it also tried to save the business--most likely because it recognized that the database object had no value (null) for LastModified, but by default, since LastModified is a DateTime, its value was DateTime.MinValue.
Once I updated the business table in the database so that LastModified is now NOT NULL, it works.
The unfortunate part of this is that the data I was working with got into this state without this being an issue.

A: As I can't comment yet, I'll post here.
If you did want the LastModified column to be nullable, the corresponding property should have been a DateTime? rather than a plain DateTime.


text:
Q: Size of Black dots and Labels position MWE:
\documentclass[12pt, letterpaper]{article}
\usepackage[a4paper,top=1 in,bottom=1 in,left=0.7 in,right=0.7 in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[misc]{ifsym}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{mathtools}
\usepackage{amssymb}
\usepackage{forest}
\usepackage{tikz,tkz-euclide,xcolor,graphicx}
\usetkzobj{all}

\begin{document}
\large

    \begin{center}
        \begin{tikzpicture}

    \tkzDefPoints{0/0/A, 9/0/B, 3/0/P, 6/0/Q}

    \draw[thick](A)--(B);

    \tkzDrawPoints[color=black](A,B,P,Q)
    \tkzDefPoint[label=below:{$A(x_1,y_1)$}](0,0){A}
    \tkzDefPoint[label=below:{$B(x_2,y_2)$}](3,0){B}
    \tkzDefPoint[label=below:{$P(x_3,y_3)$}](6,0){P}
    \tkzDefPoint[label=below:{$Q(x_4,y_4)$}](9,0){Q}
    \end{tikzpicture}
    \end{center}

\end{document}

I have two following questions.
Question : 1 How can i increase the size of black dots?
Question : 2 I want to lable cooedinates (x1 , y1) exactly below the name A instead of A(x1 , y1). I need same for rest coordinates.

A: To increase the of the dots, just add size=<length> to the \tkzDrawPoints options. If you need to move the labels down, you can add [label distance=<length>] after \begin{tikzpicture}. This will affect any other labels in there as well, alternatively place the \tkzDefPoints in a scope environment and add the option to that, or add label distance to each label.
To get the a line break in  a label, you need to set align (or text width) for the label, e.g. with
\tkzDefPoint[label={[align=center]below:$A$\\$(x_1,y_1)$}](0,0){A}

\documentclass[12pt,a4paper]{article}
\usepackage{tkz-euclide}
\usetkzobj{all}

\begin{document}
\large

\begin{center}
\begin{tikzpicture}[label distance=5pt]

\tkzDefPoints{0/0/A, 9/0/B, 3/0/P, 6/0/Q}

\draw[thick](A)--(B);

\tkzDrawPoints[color=black,size=1cm](A,B,P,Q)
\tkzDefPoint[label={[align=center]below:$A$\\$(x_1,y_1)$}](0,0){A}
\tkzDefPoint[label={[align=center]below:$B$\\$(x_2,y_2)$}](3,0){B}
\tkzDefPoint[label={[align=center]below:$P$\\$(x_3,y_3)$}](6,0){P}
\tkzDefPoint[label={[align=center]below:$Q$\\$(x_4,y_4)$}](9,0){Q}
\end{tikzpicture}
\end{center}

\end{document}


text:
Q: Create custom gradient in bootstrap 4 using SASS function theme-color-level I have setup Bootstrap 4 theme variables as follows:
// custom-theme.scss
$primary: green;
$secondary: purple;

Then custom variables like:
// custom-variables.scss
@import "~bootstrap/scss/functions";
@import "~bootstrap/scss/variables";

$idi-primary-12: theme-color-level(primary, -12);

Then importing all as follows:
//main.scss,
@import "./bootstrap-theme";
@import "./custom-variables";
@import '~bootstrap/scss/bootstrap';

This updates bootstrap classes like btn-primary and text-secondary AS EXPECTED (nice);
But the custom variable ($idi-primary-12) based on my $primary doesn't work. I was using the theme-color-level SASS function as given here in the official documentation.
When I use this in my component,
// myComponent.scss
@import "../custom-variables";

.myUserInfo {
    background-color: $idi-primary-12;
    color: color-yiq($idi-primary-12);
}

I get BLUE shade (which is the default in the bootstrap/scss/variables.scss). Github source instead of my override (green - as set above)
Question: How do I use theme-color-level function, to use my $primary (green) variable to generate a lighter version of that green? (and not the default blue).
Additional info:
official documentation for SASS functions

*

*theme-color-level uses theme-color

*theme-color extracts from object $theme-colors by key (I am using primary)

*$theme-colors primary key is set to $primary (Github for $theme-colors)

*$primary is set to blue (Github for $primary)

*This should have be overridden by my $primary = green; from custom-theme.scss. That is why btn-primary is working. (shown as green). But why isn't it using that same overridden variable to create my $idi-primary-12 variable?

A: AFAIK theme-color-level function in Bootstrap will take 2 parameters, color-name from the theme in string (eg, 'primary', 'info') and level in number as shown below:
// Request a theme color level
@function theme-color-level($color-name: "primary", $level: 0) {
  $color: theme-color($color-name);
  $color-base: if($level > 0, $black, $white);
  $level: abs($level);

  @return mix($color-base, $color, $level * $theme-color-interval);
}

and if we want to use this function for some colors other then the theme colors (eg. 'primary'), maybe we can write another function for that, eg:
@function custom-color-level($color: pink, $level: 0) {
  $color-base: if($level > 0, $black, $white);
  $level: abs($level);

  @return mix($color-base, $color, $level * $theme-color-interval);
}

with this custom function, we can pass the first param as color (eg. #007bff, orange)

A: I think you have a typo, $primary instead of primary
$idi-primary-12: theme-color-level($primary, -12);

A: theme-color-level surprisingly is not internally using the overridden $primary value. Instead it is taking the default $primary value (blue).
I was able to use other function, which directly works on my overridden $primary value.
// custom.scss
$primary: green;

darken($primary, 10% )
lighten($primary, 10% )

Reference


text:
Q: How to config a special button with image and subtitle I would like to generate the following html button with typoscript, but not yet successful after trying for hours. The image is the page image, title the page title and subtitle the page subtitle. May someone can help?

Verhalen van klanten

Wat vind jij?

I have used the following typoscript:
  tipmenu = HMENU
  tipmenu.special = directory
  tipmenu.special.value = 8
  tipmenu {
    1 = TMENU
    1 {
      expAll = 1
      wrap =
|

      NO {
        linkWrap = |

        after {
          wrap =
|

          field = subtitle
        }
      }
    }
  }

That generates the following html:

  Verhalen van klanten

Wat vind jij?

So it is still missing the image, the title is at the wrong position and the link around the subtitle is missing?

A: I'm not sure what your expected output is on multiple items, but the following code should do what you want.
But please reconsider your menu:  and
? That's how you did menus 15 years ago. Today we have HTML5 and CSS - there is no need for those ugly tags for formatting.
tipmenu = HMENU
tipmenu {
    special = directory
    special.value = 8
    1 = TMENU
    1 {
        expAll = 1
        wrap =
|

        NO = 1
        NO {
            # uncomment if needed
            # allWrap =
|

            beforeImgLink = 1
            beforeImg = GIFBUILDER
            beforeImg {
                XY = 80,80s
                10 = IMAGE
                10.file {
                    # load the first image in the media field
                    import = uploads/media/
                    import.field = media
                    import.listNum = 0
                    height = 80
                    width = 80m
                }
            }
            linkWrap =

|

            after.cObject = COA
            after.cObject {
                30 = TEXT
                30.field = subtitle
                30.typolink.parameter.field = uid
                30.wrap =
|

                wrap = |

            }
        }
    }
}


text:
Q: Best practice for having programmatically created UpdatePanel expand to fill parent container? In doing some reworking of my web application I encountered the following issue:
Although an ASP UpdatePanel does not have a height property it does not automatically expand to fill its parents container. Instead, it grows with its children's dimensions. In my scenario, the child does not have dimensions -- it should expand to fill its parents container. This causes both the UpdatePanel and its child to have very small heights.
Before I had:
[Parent Container] -> [Child Container] with both ParentContainer and ChildContainer's height property unset so that they will fill containers higher up in the hierarchy.
Now I have:
[Parent Container] -> [Update Panel] -> [Child Container]. Parent Container's dimensions are not guaranteed to be non-empty, so I am unable to programatically set ChildContainer's dimensions in all cases. As such, I would like my UpdatePanel to work in the same fashion as the controls it is wrapped around.
Is my best bet to go into the CSS and do something like:
.UpdatePanel
{
    height: 100%;
}

or do I have other, cleaner options available to me? I am creating these controls server-side, so I don't have the opportunity to wrap them in divs (nor do I want to).
EDIT:
I (can't?) use Panel instead of UpdatePanel because I would like to use the functionality of being able to update conditionally. I have a timer on my page which calls UpdatePanel.Update() on controls -- this functionality does not exist in panel AFAIK.
The body of my page is height: 100% and here is the static structure hierarchy.
The location where RadPane2 is declared is where an UpdatePanel will be slipped in. It needs to be between the RadPane and the CormantRadDockZone controls. This is only the 'base' implementation, however. Users have the ability to stack more RadPane/UpdatePanel/CormantRadDockZone 1:1:1 contents onto the page. As such, I have UpdatePanels being generated dynamically -- which means I can't apply the CSS to just an UpdatePanel's ID.
<telerik:RadSplitter ID="RadSplitter2" runat="server" BorderSize="0" Height="100%" HeightOffset="155" Skin="Web20" Width="100%" PanesBorderSize="0">
    <telerik:RadPane ID="RadPane_DefaultExpand" runat="server" CssClass="allRoundedCorners" Scrolling="None">
        <telerik:RadMultiPage ID="RadMultiPage1" Runat="server" SelectedIndex="0">
            <telerik:RadPageView ID="RadPageView1" runat="server">
                <telerik:RadSplitter ID="RadSplitter1" Runat="server" BorderSize="0" Height="100%" Skin="Web20" Width="100%">
                    <telerik:RadPane ID="RadPane1" Runat="server" CssClass="leftRoundedCorners" Scrolling="None" Width="20px">
                        <telerik:RadSlidingZone ID="RadSlidingZone1" Runat="server" ClickToOpen="True" Width="20px">
                            <telerik:RadSlidingPane ID="RadSlidingPane1" Runat="server" BackColor="#ECF4FD" IconUrl="~/Content/Dashboard/Icons/configuration.png" MinWidth="160" Scrolling="Y" TabView="ImageOnly" Title="Configuration" Width="160px" EnableDock="False">
                                <telerik:RadListBox ID="lstBxSettings" runat="server" EnableDragAndDrop="True" onclientdragging="OnClientDragging" ondropped="LstBxSettings_Dropped" Skin="Web20" Width="100%" onclientdropped="OnClientDropped">
                                    <Items>
                                        <telerik:RadListBoxItem Text="Horizontal Bar" Value="Horizontal"/>
                                        <telerik:RadListBoxItem Text="Vertical Bar" Value="Vertical" />
                                    </Items>
                                </telerik:RadListBox>
                            </telerik:RadSlidingPane>
                            <telerik:RadSlidingPane ID="RadSlidingPane2" Runat="server" IconUrl="~/Content/Dashboard/Icons/chart.png" TabView="ImageOnly" BackColor="#ECF4FD" MinWidth="160" Scrolling="Y" Title="Custom Widgets" Width="160px" EnableDock="False">
                                <telerik:RadListBox ID="lstBxCustom" runat="server" EnableDragAndDrop="True" onclientdragging="OnClientDragging" onclientdropped="OnClientDropped" ondropped="RadListBox_Dropped" Skin="Web20" Sort="Ascending" Width="100%" />
                            </telerik:RadSlidingPane>
                            <telerik:RadSlidingPane ID="RadSlidingPane3" Runat="server" BackColor="#ECF4FD" IconUrl="~/Content/Dashboard/Icons/historical.png" MinWidth="160" Scrolling="Y" TabView="ImageOnly" Title="Historical Widgets" Width="160px" EnableDock="False">
                                <telerik:RadListBox ID="lstBxHistorical" runat="server" EnableDragAndDrop="True" onclientdragging="OnClientDragging" onclientdropped="OnClientDropped" ondropped="RadListBox_Dropped" Skin="Web20" Sort="Ascending" Width="100%" />
                            </telerik:RadSlidingPane>
                            <telerik:RadSlidingPane ID="RadSlidingPane4" Runat="server" IconUrl="~/Content/Dashboard/Icons/settings_global.png" onclientbeforeexpand="ShowDashboardGlobalSettings" TabView="ImageOnly" EnableDock="False" />
                        </telerik:RadSlidingZone>
                    </telerik:RadPane>
                    <telerik:RadPane ID="RadPane2" Runat="server" BackColor="White" BorderColor="White" CssClass="rightRoundedCorners" Scrolling="None" onclientresized="OnClientResized">
                        <cc1:CormantRadDockZone ID="RadDockZone1" runat="server" />
                    </telerik:RadPane>
                </telerik:RadSplitter>
            </telerik:RadPageView>
        </telerik:RadMultiPage>
    </telerik:RadPane>
</telerik:RadSplitter>

A: UpdatePanel will translate to a div or span on client side so as long as you set the css class properly, this should work. Going via CSS is the cleanest approach.
Here's how you can set the css class (if you want to use this in a css file, make sure you've PerformSubstitution set to true):
#<%=UpdatePanel1.ClientID%> {
    height: 100;
}

Also, based on browser type, you may have to reset margin and padding to 0.
Make sure that the UpdatePanel's parent has height set too.
Update: use a Panel to wrap UpdatePanel (not substitute it)
<asp:Panel ID="Panel1" runat="Server">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    </asp:UpdatePanel>
</asp:Panel>

Noticed RadPane has a CssClass property so you can just add it there.
<telerik:RadPane ID="RadPane2" Runat="server" BackColor="White" BorderColor="White" CssClass="rightRoundedCorners myCssClass" Scrolling="None" onclientresized="OnClientResized">
    <cc1:CormantRadDockZone ID="RadDockZone1" runat="server" />
</telerik:RadPane>


text:
Q: How to set android reminder/alarm? I have got some times stored in ISO format. Some of these times are flagged to either 1(on) or 0(off) set in another column. I need to set  a reminder at the times flagged to 1, but how would I pass that each date to the reminder class?

A: There is no public API for the Alarm Clock application.
There is no public API for the Calendar application, though since it is a native UI for a Google Calendar, you could push an event over to the Google Calendar via its GData API.

A: ContentValues reminderContentValues = new ContentValues();
reminderContentValues.put(FIELD_REMINDER_EVENT_ID, eventId);
reminderContentValues.put(FIELD_REMINDER_METHOD, 1);
reminderContentValues.put(FIELD_REMINDER_MIN, minutesBefore);
mContext.getContentResolver().insert(getRemindersUri(), reminderContentValues);


text:
Q: Correct ML Terminology: Instance, Label, Example I am designing a general API for ML problems and I am trying to use a correct terminology.
What is the best way to call:

*

*the thing about which you want to make a prediction? Instance?

*the answer for the previous point? Label? I see Label as the value of the result of a prediction. How would you call an object containing a label?

*the first and second thing together (Instance and Label maybe), Example?

*the act of predicting/inferring something. What are the main differences between those 2 verbs in the ML field? Do you predict or infer something?

Is there in the ML field a specific terminology that is recognized by the community?

A: I believe different terminologies can be found, here are my suggestions after 5 years of PhD in Machine Learning, working mostly with hidden Markov models for classification, and some work on prediction.
In general, when working with a time-series we will say either observations sequence, or talk about data samples, which correspond to your first point "the thing about which you want to make a prediction?"
When doing classification, we classify samples or observations, or sequences of observations (depending on the problem that one solves) into classes. Each class can be represented by a label. It is said that a sample belongs to class A, or that the data sample is labelled A.
Prediction is the act of guessing/predicting the next thing that is going to happen. There is the idea of "future" in it (though I've seen the term used sometimes for algorithms like the Viterbi algorithm, but I have always found it confusing for people...).
Inference is more used in an estimation framework. You can use inference methods to train a model for example.
Usually (from what I have seen and use) packages will have methods called train to train/estimate a model (or fit sometimes), which makes it clearer that infer. I would avoid using this confusing word in general.
Hope this help, and open to discuss more in the comments.


text:
Q: Handling NoneType when using addition Im trying to add some values up but some of the values have a NoneType value.  Now I looked at this question but I need some help.  Im hoping someone can explain to me how I can get this to work with django.
Here is my for loop in my views.py:
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year)
for inv in next_il:
   total_m2 += inv.maturity_amount

Now inv.maturity_amount is the value I'm trying to handle that has NoneType.
Any suggestions would be greatly appreciated.
Thanks.
Steve

A: for inv in next_il:
   total_m2 += inv.maturity_amount or 0

And may be you should set default=0 for maturity_amount field.
And it's better to use DB aggregation here:
from django.db.models import Sum

total_m2 = Investment.objects.filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year).aggregate(Sum('maturity_amount'))

A: Two choices that occur to me.
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year)
for inv in next_il:
   total_m2 += 0 if inv.maturity_amount is None else inv.maturity_amount

I actually like this better:
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year)
for inv in next_il:
   try:
       total_m2 += inv.maturity_amount
   except TypeError:
       log.warning( "Null maturity amount" )


text:
Q: Visual Studio ASP.NET/HTML reformat capability - does it exist? Does Visual Studio have a capability, or is there a VS plug-in, that will reformat ASP.NET and HTML markup (i.e. perform pretty printing). Specifically, I want it to put all properties or attributes in alphabetical order for each tag, possibly with some exceptions that the user can specify, say in a config file. Also, each property or attribute could optionally be put on an individual line, again per the user's specification.
For example consider the following:
<asp:TextBox ID="txtPlanStart" runat="server" ToolTip="start date" Columns="8">

The reformatted version would be:
<asp:TextBox ID="txtPlanStart" runat="server"
     Columns="8"
     ToolTip="start date" />

Note that the reformatted version not strictly in alphabetical order or on separate lines, because ID and runat come first. Again exceptions to the reformatting could be specified by the user.
If this capability is not available integrated in VS, is there some other utility available?

A: Yes, you can use the shortcut CTRL + K + D to reformat ASP.NET and HTML markup!

A: I don't think Visual Studio has this functionality built it but the Resharper plugin has this is a contextual option. It will let you click on any tag and choose to have it re-order them alphabetically.


text:
Q: Why is this wont work in BATCH, FOR command? Standallone it works I want to export images from films, as thumbnail, I'm using ffmpeg. My batch command:
DEL *.jpg

setlocal
dir *.mp4 /a:-d /b > foldersTemp.txt
FOR /f %%A IN (foldersTemp.txt) DO ffmpeg -i %%A -vf fps=1/200 %%Athumb%04d.jpg
endlocal

DEL foldersTemp.txt

but it only creates only one per film. If I use the ffmpeg command, it works. I'm afraid the % confuses the command

A: Your file names likely contain spaces.
Add the parameter "tokens=*" to pull the whole line (rather than delimited by a space).  Also, you will also need to surround your output filename with double quotes.
FOR /f "tokens=*" %%A IN (foldersTemp.txt) DO ffmpeg -i %%A -vf fps=1/200 "%%Athumb%%04d.jpg"


text:
Q: PHP time-ago and time in the future I have a function to get the Time-ago from a Timestamp, I grabbed it somewhere from the internet and developed and optimized it. It's fully functioning. The problem here is that it ONLY gets time-ago (from a past Timestamp), it didn't process future Timestamps (It returns 0 seconds ago).
Is anybody able to help me add this functionality to the function?
<?php

function time_ago( $ts, $format ) {

    // $format = 'l, F d, Y H:i';

    $granularity    = 1;

    $dif            = time() - $ts;

    if ( $dif < 0 )

        return '0 Seconds ago';

    elseif ( $dif < 604800 ) { // 604800 7 days / 864000 10 days

        $periods = array(

            'Week'      => 604800,
            'Day'       => 86400,
            'Hour'      => 3600,
            'Minute'    => 60,
            'Second'    => 1

        );

        $output = '';

        foreach ( $periods as $key => $value ) {

            if ( $dif >= $value ) {

                $time = round( $dif / $value );

                $dif %= $value;

                $output .= ( $output ? ' ' : '' ) . $time . ' ';

                $output .= ( ( $time > 1 ) ? $key . 's' : $key );

                $granularity --;

            }

            if ( $granularity == 0 )

                break;

        } // foreach( $periods as $key => $value )

        return ($output ? $output : '0 seconds') . ' ago';

    } else

        return date( $format, $ts );

}

?>

A: This should work
<?php
function diffPeriods($diff)
{
    $periods = array(
        'Week' => 604800,
        'Day' => 86400,
        'Hour' => 3600,
        'Minute' => 60,
        'Second' => 1
    );

    $granularity = 1;

    $output = '';
    foreach ($periods as $key => $value) {

        if ($diff >= $value) {

            $time = round($diff / $value);

            $diff %= $value;

            $output .= ($output ? ' ' : '') . $time . ' ';
            $output .= (($time > 1) ? $key . 's' : $key);

            $granularity --;
        }

        if ($granularity == 0) {
            break;
        }
    }

    return $output;
}

function time_ago($ts, $format)
{
    $diff = time() - $ts;

    if ($diff == 0) {
        return 'Now';
    }

    if ($diff < 604800 && $diff > 0) {
        // 604800 7 days / 864000 10 days

        $periods = array(
            'Week' => 604800,
            'Day' => 86400,
            'Hour' => 3600,
            'Minute' => 60,
            'Second' => 1
        );

        $output = diffPeriods($diff);

        return ($output ? $output : '0 seconds') . ' ago';
    } elseif ($diff < 0 && $diff > - 604800) {
        $output = diffPeriods($diff * - 1);

        return 'in ' . ($output ? $output : '0 seconds');
    }

    // too old/new...display the date
    return date($format, $ts);
}

var_dump(time_ago(time(), 'l, F d, Y H:i')); // now
var_dump(time_ago(time() + 3600, 'l, F d, Y H:i')); // 1 hour in the future
var_dump(time_ago(time() + (3600 * 50), 'l, F d, Y H:i')); // 2 daysin the future
var_dump(time_ago(time() + (3600 * 24 * 11), 'l, F d, Y H:i')); // 11 days in the future
var_dump(time_ago(time() - 3600, 'l, F d, Y H:i')); // 1 hour ago
var_dump(time_ago(time() - (3600 * 50), 'l, F d, Y H:i')); // 2 days ago
var_dump(time_ago(time() - (3600 * 24 * 11), 'l, F d, Y H:i')); // 11 days ago

A: I've edited your function. Now it displays a time in the future as In 10 Hours.
Code:
function time_ago( $ts, $format ) {

    // $format = 'l, F d, Y H:i';
    $granularity    = 1;
    $dif            = time() - $ts;
    $future = $dif < 0 ? true : false;
    $dif = abs($dif);
    if ( $dif < 604800 ) { // 604800 7 days / 864000 10 days
        $periods = array(
            'Week'      => 604800,
            'Day'       => 86400,
            'Hour'      => 3600,
            'Minute'    => 60,
            'Second'    => 1
        );
        $output = '';
        foreach ( $periods as $key => $value ) {
            if ( $dif >= $value ) {
                $time = round( $dif / $value );
                $dif %= $value;
                $output .= ( $output ? ' ' : '' ) . $time . ' ';
                $output .= ( ( $time > 1 ) ? $key . 's' : $key );
                $granularity --;
            }
            if ( $granularity == 0 )
            break;
        } // foreach( $periods as $key => $value )
        if($future) {
            return "In " . ($output ? $output : '0 seconds');
        } else {
            return ($output ? $output : '0 seconds') . ' ago';
        }
    } else
    return date( $format, $ts );
}


text:
Q: Calling python shell apps from ruby (rails) How can I call python running in shell from ruby. Actually I need ruby to communicate with some app running under the python in shell. So I need ruby to call python (command 'python') in cmd and then import libraries (command 'import xyz') under the python environment, and thne run functions of this imported libraries (for example 'xyz.showdate()'), and get result of course.
I tryed to use IO.popen and Open3.popen3 functions to achieve this, but I do something wrong.
Actually I use jruby on rails, but it should be same with ruby, I guess.

A: You probably don't really want to be doing this, this is going to make your ruby script excessively convoluted when you could probably get the result directly in ruby.
If you however decide to go that way, you could create a python script that does what you need and run it from the ruby script:
# python-script.py
import xyz
if __name__ == '__main__':
    xyz.showdate()

You would then arrange so that your ruby script calls the following command:
python path/to/python-script.py

Provided your xyz.showdate prints the date, you can collect standard output to get the result.
But again, that's probably not a great idea.


text:
Q: Do unit normal vectors of extremal points on a compact hypersurface have opposite directions? Problem
To be definite, by a hypersurface of $\mathbb R^{n+1}$, I mean a connected submanifold of $\mathbb R^{n+1}$ of dimension $n$ without boundary.
Suppose $M$ is a compact smooth orientable hypersurface of $\mathbb R^{n+1}$ with the Gauss map $N\colon M\to S^n$ and $0\neq v\in\mathbb R^{n+1}$. Let $f_v(x)=\langle x,v\rangle$ be a so-called height function. Since $M$ is compact, we can take a maximal point $p\in M$ and a minimal point $q\in M$ of $f_v$ restricted on $M$. It's not difficult to show that $N(p),N(q),v$ are collinear. Is it true that $N(p)+N(q)=0$, i.e., $N(p),N(q)$ are of opposite direction?
Discussion
If $M$ is a level hypersurface, i.e., the zero set of a submersion $F\colon\mathbb R^{n+1}\to\mathbb R$, then the statement is true. The idea of the proof is depicted as follows. Take a sufficient large sphere $S\subseteq\mathbb R^{n+1}$, and then we can use it to construct a continuous path $\alpha\colon[a,b]\to\mathbb R^{n+1}$, differentiable at $p$ and $q$, such that $\alpha(a)=p,\alpha(b)=q,\alpha'(a)=\alpha'(b)=v$, but $\alpha(t)\not\in M$ for $a<t<b$. For more details, see J. A. Thorpe's Elementary Topics in Differential Geometry, Chapter 6, page 33.
If the compactness is removed, even if $f_v$ attains its maximum and minimum, the statement is false. Consider $n=1$ and $M$ to be the graph of $y=\sin x$ and take $v=(0,1)$.
I heard that there's a magic theorem that any compact (smooth) hypersurface in $\mathbb R^{n+1}$ is a level hypersurface and therefore orientable. I don't want to appeal to such a theorem. I want a direct proof for this.
Any idea? Thanks!

A: Discussion:
What you're trying to show is global in nature. The example of the sinusoidal curve you describe in $\mathbb{R}^2$ or the twice-twisted annulus Behaviour describes in $\mathbb{R}^3$ shows this. You'll need techniques that respect this global nature of your result.
The result you want, being global in nature, seems to me just as hard to prove as the statement that any closed, connected, dimension $n$ submanifold $M$ of $\mathbb{R}^{n+1}$ separates $\mathbb{R}^{n+1}$ into an unbounded piece and a bounded piece (i.e. $\mathbb{R}^{n+1}-M$ has two components, one unbounded and one bounded) such that, at $p \in M$, one (local) side of $M$ is in the unbounded component, and the other (local) side of $M$ is in the bounded component.
This fact actually proves that $M$ is oriented, where the orientation is given by a normal vector pointing into the unbounded component, say. (The other choice would be pointing into the bounded component.)
It also proves your result: There are only two orientations on a connected, oriented manifold, so your orientation must be one of these two. Then, at the max the unbounded component is necessarily up and at the min the unbounded component is necessarily down, giving one orientation satisfying what you want; the other orientation swapping both of these also does what you want.
You need some techniques to give a global result like this. Transversality is the standard tool to do this in differential topology. There are also algebraic topology techniques that would prove this. I'll describe the transversality techniques and how to prove this below.

General Transversality Counts:
A nice reference for the following would be Differential Topology by Guillemin and Pollack.
The mod $2$ transversality intersection count of two submanifolds $A$ and $B$ of dimension $n$ and $k$ inside an $n+k$ dimensional manifold is a count of the number of times they intersect modulo $2$, in the case when they intersect transversally (i.e. "go straight across" each other; the technical condition is that $TA_p + TB_P = TM_p$). When they don't, it's defined by homotoping them slightly so they do intersect transversally and then counting (a general theorem states that such a homotopy is always available and can be made very small in any appropriate sense).
This count is invariant under homotopies in general, which is a way of saying it is getting at something global in nature. The fact that our counts were mod $2$ was essential for this, and the intuitive idea is that if we introduce new intersections by a homotopy, they always come in pairs: for example, think of passing a curve across a line, generating two intersection points. (In the case when everything has an orientation, we can also define these counts with signs, but that won't come into play here.)
This is defined even in the case where $A$ and/or $B$ has boundary, as long as we specify that the boundaries are disjoint and are required to remain so under homotopy. It's also defined when one of the manifolds is non-compact, so long as it's proper (intuitively, runs off to infinity, so that after some point it doesn't interact with the other; formally this means that any compact subset of the ambient manifold intersects it in a compact set).

The transversality counts for this situation:
Let $M$ be a connected, closed, dimension $n$ sub manifold of $\mathbb{R}^{n+1}$.
Given a point $x \in \mathbb{R}^{n+1}-M$, define $m_x$ as the mod $2$ transverse count of intersections of any half-infinite ray starting at $x$ and $M$.
I claim this is independent of the ray chosen. To see this, consider two rays. I claim they have the same count mod $2$. Stick the two rays together. We must show this $V$ shape intersects the manifold zero times mod $2$. To see this, close it up by a circular arc at some large distance (out past some finite ball that $M$ is contained in). Then we have a closed circle in $\mathbb{R}^{n+1}$ we are intersecting with $M$ with the same mod $2$ intersection count as our $V$ shape. But any circle in $\mathbb{R}^{n+1}$ is homotopic any other; in particular it's homotopic to a tiny circle that misses $M$, so the count is zero mod $2$.

Using the counts:
We are to show that there are precisely two components to $\mathbb{R}^{n+1} - M$, an unbounded component and a bounded component.
Let $C_0 = \{x \in \mathbb{R}^{n+1} - M : m_x = 0\}$ and $C_1 = \{x \in \mathbb{R}^{n+1} - M : m_x = 1\}$.
These are disjoint and are also open (by the fact the counts remain the same under homotopy where the boundary point of the ray doesn't hit $M$).
Additionally, near any point in $M$, by the local form of an immersion, points on opposite sides locally have counts that differ by $1 \mod 2$.
Finally, every point outside a large ball containing $M$ must be in $C_0$ (take a ray heading outward, away from the ball), so that's the unbounded one and $C_1$ is bounded.
This finishes the claim up in the discussion section, which then proves your result as discussed there.

It isn't necessary to actually show each of $C_0$ and $C_1$ is connected, but here's a summary of that:
To see each is connected, I claim that a tubular neighborhood $T$ of $M$ (see Guillemin & Pollack e.g. for discussion of this if it isn't familiar) in $\mathbb{R}^{n+1}$ such that $T-M$ has at most two components. The at most two components part can be seen by local form for an immersion plus the fact that any two points in $M$ can be connected by a compact arc.
Now, from any point $x \in C_0$, draw a ray starting at $x$. This ray has a first time it hits $M$. Just prior to that it was inside $T-M$. This shows that any two points in $C_0$ are in the same connected component of $C_0$. Similarly for $C_1$.


text:
Q: How to insert the same record into the database a number of times? I have a numeric PHP variable named $quantity and based on the number set in this variable, I want to insert the same record in the MySQL table.
Example:
$quantity = '4';

$sql1 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql2 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql3 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql4 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";

A: You can achieve this by using a loop and a prepared statement. You need to execute the same statement multiple times. This is also very useful if the values are dynamic and they could change, e.g. the values are coming from user input.
Prerequisite:
You need to open a connection to your database. If you use MySQL then the connection would look something like this:
$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'username', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

Now you can prepare a statement which we will execute in a loop multiple times.
$stmt = $pdo->prepare("INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());");

You can use any loop you like but for a simple scenario where we want the same code to be executed a number of times, a while loop is sufficient.
$quantity = 4;
while ($quantity--) {
    $stmt->execute();
}

If it is easier for you, you can use for loop, too.
for($quantity = 0; $quantity < 4; $quantity++) {
    $stmt->execute();
}

A: Try something like this:
// NOTICE - Make sure you are escaping any end-user supplied values correctly - See PHP docs for examples of how
$sql_template = 'INSERT INTO `table_quantity` (`username`, `code`, `quantity`, `data`) VALUES (\'John\', \'34438\', \'1\', now());';
$quantity     = 5;
$sql          = '';

foreach (range(1, $quantity) as $i) {
  $sql .= $sql_template;
}

echo $sql;

See the following docs for explanations:

*

*foreach

*range()

*append to string

*Escape SQL values with PDO

*Escape SQL values with MySQLi


text:
Q: How to use a different database host in development vs deployment? I'm new to Python and Django and have over the past few weeks managed to set up my first deployment - a very basic site with user authentication and a few pages, which I hope to fill with content in the next couple of weeks.
I have managed to find the answer to probably 40+ questions I have encountered so far by searching Google / StackOverflow / Django docs etc., but now I have one I can't seem to find a good answer to (perhaps because I don't know how best to search for it): when I develop on my local machine I need my settings.py file to point to the remote database ('HOST': 'www.mysite.com',) but when I deploy to a shared hosting service provider they require the use of localhost ('HOST': '', in settings.py).
Since I host my code on GitHub and want to mirror it to the server, is there a way to resolve this so I don't have to make a manual edit to settings.py each time after uploading changes to the server?

A: You can have two copies of your settings.py file, one for production and one for development. Whatever you need to be the default, name it as settings.py
Just set DJANGO_SETTINGS_MODULE to the python path for the file that you would like to use.
So, if your settings files are myproject/settings.py, myproject/settings_dev.py; you can then do:
$ DJANGO_SETTINGS_MODULE=settings_dev python manage.py shell
From the myproject directory.

A: You can create a local_settings.py file which you can put it in .gitignore and include it in the original settings.py. Put every environment sensitive variable in this file (DATABASES, DEBUG, CACHES, MEDIA_URL etc.)
In settings.py:
try:
    from local_settings import *
except ImportError:
    pass

In .gitignore:
*/local_settings.py

I recommend you to put a local_settings.py.example next to the setting files which will be in the gitrepo. This way any time you deploy to a new environment you just need to copy this example and change the necessary lines.


text:
Q: Is there a beginner's guide to Battlefield 3 multiplayer? Is there a guide that explains the different types of multiplayer matches that I can take part in? Also, is there a list of the different unlocks that I can get for the various classes that I play on my Battlefield 3 account?
Finally, could someone please explain to me the HUD in detail to me (both for ground combat and for when you're inside of vehicles)?

A: If you're willing to pay a few extra dollars ($10 at Best Buy, $12.50 at Amazon), the Battlefield 3 Official Game Guide from Prima is impressive. You could shell out way more for the hardcover Limited Edition version, but I don't recommend that.
The first 20-ish pages are a primer with a quick but surprisingly thorough overview of basic game concepts. Then it goes into tons of detail for any class, vehicle, map, or game time you'd like to learn more about.
If you're not up for the extra dollars, I don't know of a great online overview yet. Often major gaming sites will put together game guides or walk-throughs, but usually not this early. IGN has a really pretty good start to a guide which may get better over time. I don't see coverage of some really basic stuff like the elements of the HUD, but you can get that from the official guide (which is has pretty limited value otherwise).
For most games wikia.com in an excellent resource. It's usually most helpful when you want to answer a specific question than when you're looking for an overview. The Battlefield 3 Wikia site is coming together.

A: This is kind of hard to answer because it's not exactly clear what the question is.
There are two primary game modes in Battlefield 3.

*

*Conquest
Capture and hold points A-E. To capture stand near a point. The more people standing near the point, the faster it captures or uncaptures. The more points you hold, the faster the opposing team's lives go down over time. When one of the team's lives gets to zero, they lose.

*Rush
One team plants a bomb on objectives A and B, the other team tries to prevent/defuse. Game is over when the attacking team runs out of lives (displayed in the lower left) or all the objectives are destroyed.
There's also deathmatch and team deathmatch, everyone hopefully knows what those are by now...
In general, this is my advice to new Battlefield 3 players:

*

*Spot everything, all the time. The spot key (or button; it's q on PC, back on Xbox, and select on PS3) lets everyone else on your team know where the bad guys and vehicles are. Spot spot spot spot! If you do nothing else for your team, please spot baddies! Always! This should be instinctive.

*Don't ever go anywhere alone. Buddy up. Find your squadmates (in green) and follow them around. If you are not in a squad, join one using the SQUAD tab on your loadout screen. If your squad is filled with idiots, leave the squad and find another. Try to pick squads with players of higher rank so they aren't beginners and at least in theory know what they are doing.

*Always spawn on your squadmates when possible. Choose your spawn point via the DEPLOY tab on your loadout screen, which will include each of your squadmates, provided they are still alive. If you cannot spawn on your squadmates, spawn at a nearby point -- perhaps not too close, if you are getting killed a lot, to give you time to approach the action without appearing in the middle of it.

*Move from  cover to cover. Don't just run down the middle of a field or street. Pick one piece of cover, then pick a path to the next piece of cover toward your objective. Repeat until you arrive.

*Play the objective. Those big visible A-E letters are what everyone is fighting over. Just shooting bad guys is not enough. If you want to win, help your team achieve the objectives of the map.

*Half of the battle is knowing the map. It helps a lot to know the common entry and exit points on the map, because otherwise it feels random -- like anyone can be coming from anywhere! Try to stick to one map for a bit and learn it reasonably well, before moving on to the next "never seen this before, no idea where anyone is going" map.

*Use a microphone. Talking to your teammates is very helpful. Try and get in a squad where others are talking, and talk to them. This is a great way to improve your game - you'll become more aware, work better together, and maybe even pick up tips from more experienced players.
Of course there is tons more, but that's the essentials.

A: To add to Jeff's answer: Be useful...
If you are a medic, be liberal with handing out medikits.  Whenever you dash and stop, leave a medikit.  See a team mate, drop a medikit.
Same with support: leave plenty of ammo boxes.  For some of the urban maps, grenades become very useful so your team mates will like you when you replenish them.
Don't run around aimlessly.  If in doubt, find cover and look about for baddies and try to spot them.  If you run around 'looking for action' then you WILL get shot. Or knifed. Or RPG'd!
If your team arm the MCOM, then don't just stand there looking at it! Turn around and look out for the defenders coming to disarm it.  If your team mate looks left, then look right and cover his six. Scan the rooflines. Spot spot and spot.
If you have a headset (when it works) then don't speak drivel and yammer on and on.
If you get into a tank or vehicle as the second passenger then use the machine gun to spot, to kill engineers and recon's with a handful C4 running up to toast you.  Don't look forwards (the same way the driver is driving) but look-out to the left and right and behind and up (where the driver can't see) and take out infantry, choppers, jets etc.
Oh, and remember to blink! Your eye's can get very dry and sore after a couple of good games!


text:
Q: How many $n$-digit automorphic (circular) numbers are there? How many $n$-digit numbers $a$ are there s.t. $a^2$ ends in $a$?
Using Chinese Remainder Theorem it is easy to calculate what these $n$-digit numbers are,
$$x\equiv0\ \left(mod\ 2^n\right)\\
x\equiv1\ \left(mod\ 5^n\right),$$
and
$$x\equiv1\ \left(mod\ 2^n\right)\\
x\equiv0\ \left(mod\ 5^n\right),$$
we obtain such numbers.
But my question is, how many $n$-digit numbers are there?
So far I have that there is an "upper" limit of $2n$ and a "lower" limit of $n$, but apart from that I don't know derive such a formula to calculate how many there are.
Is there a formula to show how many there are?
Thanks in advance.

A: Automorphic numbers must end in $0,1,5$, or $6$
As indicated by @Arnold D. here,
I showed that the only automorphic numbers that end in $0$ or $1$ are $0$ and $1$.
I also showed that the automorphic numbers that end in $5$ or $6$ occur in sequences. The first $6$ are shown below
     5² =           25      11-       5 =      6  and       6² =          36
    25² =          625     101 -     25 =     76  and      76² =        5776
   625² =       390625    1001 -    625 =    376  and     376² =      141376
  0625² =       390625   10001 -   0625 =   9376  and    9376² =    87909376
 90625² =   8212890625  100001 -  90625 =  09376  and   09376² =    87909376
890625² = 793212890625 1000001 - 890625 = 109376  and  109376² = 11963109376

The table is meant to emphasize that the $(n+1)^{th}$ automorphic number that ends in $5$ can be found by looking at the last $n+1$ digits of the square of the $n^{th}$ automorphic number that ends in $5$.
The $n^{th}$ automorphic number that ends in $6$ is equal to $10^n+1$ minus the value of the $n^{th}$ automorphic number that ends in $5$.
Note that we must cound $0625$ as a four-digit number if we want to count $0625^2 = 390625$ as an automorphic number.
In which case, the answer to your question is $2$.


text:
Q: Openshift 4 - CRC - ImagePullBackOff: cannot access local docker daemon to pull image, as it's using HTTP and not HTTPS I am using CRC in my local machine and when I deploy with ansible, I see pods in ImagePullBackOff status, because it cannot pull the image. The image is named "some-interal-regsitry:5000/my-image` but actually the image is in local docker daemon. It's local so using HTTP and not safe.
How can I change the settings of Openshift to allow local docker daemon pulling?

A: Open CRC local page http://console-openshift-console.apps-crc.testing, find in left menubar, "Home" - "Overview", find in right view, "Details" - "View settings",  top tabs, "Configurations", scroll down to "Image", enter, top tab, "YAML", add this part under "spec".
spec:
  additionalTrustedCA:
    name: registry-certs
  registrySources:
    insecureRegistries:
      - 'some-interal-regsitry:5000'

So HTTP is not blocked anymore.
And you need to add the similar into /etc/docker/daemon.json so it would be like:
{
 "bip": "xxxxx",
 "fixed-cidr": "xxxxx",
 "mtu": 1400,
 "dns": ["xxxx", "xxxx", "xxxx"],
 "insecure-registries" : [ "some-interal-regsitry:5000"]
}


text:
Q: Document metadata are replaced after uploading document again in o365 I have created a document library in o365. In o365 a new button is showing at the top of the document library "Upload". Now I have uploaded a document and added some metadata to that. Now when I am uploading document again using "Upload" button it is replacing all existing values.

A: This is by design in versioning enabled Document Library.
Document Properties not carry to new version
http://blog.fpweb.net/sharepoint-2010-versioning/


text:
Q: Why do floats change the \mark? The presence of floats appears to disrupt the setting of \marks, so that \topmark ends up with the wrong value.
For example, consider this:
\documentclass{article}
\textheight 50mm
\textwidth 50mm

\makeatletter \def\@oddhead{[\topmark/\firstmark/\botmark]} \makeatother

\def\block#1{\textbf{#1}\mark{#1}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
Foo bar baz.\par}

\begin{document}

\block a
\block b
\block c
\block d
%\begin{figure}\hrule width 1pt height 20mm depth 0pt \end{figure}
\block e

\end{document}

That works as it should: the page break appears in the middle of block 'c', blocks 'd' and 'e' start on page 2, and the header therefore shows '[c/d/e]'.  That's correct.
If I uncomment the {figure} line, however, then the 'figure' appears on page 3, and page 2 is unchanged (page breaks within blocks 'c' and 'e'), but the header now shows '[d/d/e]'.
I am perplexed as to why this happens.  I can't find anything in \@float or \@caption which touches the marks, and in general nothing in latex.ltx that uses \markboth or \markright (which are the only things in latex.ltx which call \mark).   article.cls has a few things that call \@mkboth, but they're associated with \@part, and with lists of figures and the index.
What is it I'm missing?

A: If the question is how to use top marks, see my package titleps. See also How to add "cont." section title to the top of pages? .

A: Answering my own question...
The problem here is, bluntly, that LaTeX messes up the TeX \mark system: \firstmark and \botmark still work, but \topmark doesn't.  This is because LaTeX's float algorithm, which handles \marginpar as well as figures and tables, can invoke the output routine at times other than between pages.  That necessarily moves \botmark into \topmark in a way which means that \topmark is no longer the value that \botmark had at the end of the previous page.
LaTeX's \markboth system uses the TeX \mark system, but is specialised to the case of running section headings, and doesn't seem repurposable.
The multicol and fixltx2e packages (and the fixmarks package, which they both cite) address this problem for the case of multi-column pages, but not in a way which makes \topmark work in the case illustrated here.
My particular case is this: I'm setting exam papers, and want to put a [Qx cont'd] at the top of pages which start in the middle of question x.  I had beeing putting \mark{x} at the beginning of each question: testing \topmark worked fine, until the paper included figures.  I've got it working in a slightly clunky way.  I put \mark{1x} at the beginning of each question, and \mark{0x} at the end: I can then tell by looking at the number at the beginning of \firstmark whether I'm still in a question or not.
Edit: while that's a nice idea, it turns out that the a more effective solution is to save the \botmark manually, with \xdef\my@topmark{\botmark} in the page footer.  This can be examined in the following page header, where it has (exactly?) the same semantics as \topmark.  There might be some pathological cases where this doesn't work, but I haven't run into them.


text:
Q: Linear Regression: Is there a difference in the model between using ML instead MSE? We know we need 4 things for building a machine learning algorithm:

*

*A Dataset

*A Model

*A cost function

*An optimization procedure

Taking the example of linear regression (y = m*x +q) we have two most common way of finding the best parameters: using ML or MSE as cost functions.
We hypotize data are Gaussian-distributed, using ML.
Is this assumption part of the model, also?
It it's not, why? Is it part of the cost function?
I can't see the "edge" of the model, in this case.

A: The assumption that the data is Gaussian-distributed is part of the model in the sense that, for Gaussian distributed data the minimal Mean Squared Error also yields the maximum liklelihood solution for the data, given the model parameters. (Common proof, you can look it up if you are interested).
So you could say that the Gaussian distribution assumption justifies the choice of least squares as the loss function.

A:
Is this assumption part of the model, also?

Yes it is. The ideas of different loss functions derived from the nature of the problem, consequently the nature of the model.
MSE by definition calculates for the mean of the squares of the errors (error means the difference between real y and predicted y) which in its turn will be high if the data is not Gaussian-Like distributed. Just imagine a few extreme values among the data, what will happen to the line slope and consequently the residual error?

It is worth mentioning the assumptions of Linear Regression:

*

*Linear relationship

*Multivariate normality

*No or little multicollinearity

*No auto-correlation

*Homoscedasticity

If it's not, why? Is it part of the cost function?

As far I have seen, the assumption is not directly related to the cost function itself, rather related -as above-mentioned- to the model itself.
For example, Support Vector Machine idea is separation of classes. That's finding out a line/ hyper-plane (in multidimensional space that separate outs classes), thus its cost function is Hinge Loss to "maximum-margin" of classification.
On the other hand, Logistic Regression uses Log-Loss (related to cross-entropy) because the model is binary and works on the probability of the output (0 or 1). And the list goes on...


text:
Q: android java playing wav audio file from sd card I`ve troubles to play a wav audio file from sd card:
This is my code:
mp = new MediaPlayer(); //Defined as MediaPlayer above
        try {
            mp.setDataSource(fileNamePath);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

The fileNamePath is in this format: /storage/emulated/0/MyApp/name.wav
This is the error code I get:
E/MediaPlayer: stop called in state 1, mPlayer(0x0)
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)

I hope you can help me here?
Thanks!

A: Android media player have some troubles with some wav files, I recommend you to use AudioTrack instead of MediaPlayer.
Here is a example:
     new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // just put here your wav file
                File yourWavFile = new File(Environment.getExternalStorageDirectory() + "/" + AUDIO_FOLDER, fileName);
                FileInputStream fis = new FileInputStream(yourWavFile);
                int minBufferSize = AudioTrack.getMinBufferSize(16_000,
                AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
                AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 16_000,
                AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
                    minBufferSize, AudioTrack.MODE_STREAM);

                int i = 0;
                byte[] music = null;
                try {
                        music = new byte[512];
                        at.play();

                        while ((i = fis.read(music)) != -1)
                            at.write(music, 0, i);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    at.stop();
                    at.release();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();


text:
Q: Prevent duplicate claims added via AddClaimAsync We're using ASP.NET Identity in an MVC 5 app. We have a page that allows users and their claims to be added by admin. However, using the following lines, I can keep adding a user with the same role claim, thus creating duplicate items (the AspNetUserClaims table has an "autonumber" column for the primary key so we can keep adding the same role to the same user):
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
await userManager.AddClaimAsync("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    new Claim(ClaimTypes.Role, "SomeRole"));

Note that I'm adding a claim for an arbitrary user, not the logged on user. If it were the logged on user, I could simply call User.IsInRole("SomeRole"). And the xxxx is the user's GUID.
In this scenario, I'm thinking of using the following DB call to check before adding a role:
public static async Task<bool> UserHasClaim(string userId,
    string claimType, string claimValue)
{
    using (var db = new MyEntities())
    {
        return await db.AspNetUserClaims
            .AnyAsync(x => x.UserId == userId && x.ClaimType ==
                  claimType && x.ClaimValue == claimValue);
    }
}

Is there a better way to do this? I know that the ClaimsPrincipal contains a method .HasClaim(...) but I can't figure out how to create a ClaimsPrincipal from that user and then run the method. Thanks.


text:
Q: Using Excel "IF" Statment To Filter Out Text Beginning Or Ending With A Certain Character Working on the same project as before and I need to find a way to to write an "IF" statement that will search for words beginning with a "<" as well as words that end with a " \ ".  I would like to conditionally highlight those cells with the value "IGNORE: HIDDEN FIELD".
I searched around and found that there is a SEARCH function in Excel but that doesn't seem to be what I'm looking for.
Is anyone aware of how to do this?  "If a cell begins with a "<" or ends with a " \ " then blah blah blah".

A: Try,
=IF(OR(LEFT(A1)={"<","\"}),"blah-blah-blah", "")

That formula covers cell values beginning with either a less than or backslash. If the backslash should be checked at the end of the cell value then this would be more appropriate.
=IF(OR(LEFT(A1)="<",RIGHT(A1)="\"),"blah-blah-blah", "")

The LEFT() and RIGHT() functions default to a single character so if only the first character from either direction is to be examined the num_chars parameter is not required.

A: To match words that start with < and end with \, use
=IF(AND(LEFT(A1,1)="<",RIGHT(A1,1)="\"),TRUE,FALSE)
To match words that start with < and / or end with \, use
=IF(OR(LEFT(A1,1)="<",RIGHT(A1,1)="\"),TRUE,FALSE)
Cell A1 contains the word to test. This can form the basis of your conditional formatting test. If you want to display alternative text then replace TRUE and FALSE to suit personal taste, e.g. IGNORE: HIDDEN FIELD and A1 respectively.

A: Looks like you can use SEARCH()
=IF(OR(SEARCH("\";A1;1)=LEN(A1);SEARCH("<";A1;1)=1); "blahblahblah";"blahblahblah")

A: You could do the same job without IF
Replace function (CTRL+F) and "*" operator.
Press CTRL+F
Type "<*" to look for values that cells witch content begins with<
Than replace for whatever you want.
Type "*/" to find cells that's values end with /
Than replace it for whatever you want.
Or even better you could use Conditional Formating, it has one option for highlighting the cells that begins with a certain character.


text:
Q: Managed (Release) package upgrade error I have a release managed package 1.0 installed on my scratch org and now I'm upgrading to 1.1 released managed package but I'm getting this error: what does it mean?

This app can't be upgraded. There are problems that prevent this
package from being installed. Install failed  Your requested install
failed. Please try this again. None of the data or setup information
in your salesforce.com organization should have been affected by this
error. If this error persists, contact salesforce.com Support through
your normal channels and reference number: 1031024430-648351
(279340770)


text:
Q: Strict-Mode: Alternative to argument.callee.length? Javascript: The Definitive Guide (2011) has this example (p.186) that doesn't work in strict mode but does not show how to implement it in strict mode--I can think of things to try but am wondering about best practices/security/performance--what's the best way to do this sort of thing in strict mode?  Here's the code:
// This function uses arguments.callee, so it won't work in strict mode.
function check(args) {
    var actual = args.length;          // The actual number of arguments
    var expected = args.callee.length; // The expected number of arguments
    if (actual !== expected)           // Throw an exception if they differ.
        throw Error("Expected " + expected + "args; got " + actual);
}

function f(x, y, z) {
    check(arguments);  // Check that the actual # of args matches expected #.
    return x + y + z;  // Now do the rest of the function normally.
}

A: You could just pass the function you're checking.
function check(args, func) {
    var actual = args.length,
        expected = func.length;
    if (actual !== expected)
        throw Error("Expected " + expected + "args; got " + actual);
}

function f(x, y, z) {
    check(arguments, f);
    return x + y + z;
}

Or extend Function.prototype if you're in an environment that will allow it...
Function.prototype.check = function (args) {
    var actual = args.length,
        expected = this.length;
    if (actual !== expected)
        throw Error("Expected " + expected + "args; got " + actual);
}

function f(x, y, z) {
    f.check(arguments);
    return x + y + z;
}

Or you could make a decorator function that returns a function that will do the check automatically...
function enforce_arg_length(_func) {
    var expected = _func.length;
    return function() {
        var actual = arguments.length;
        if (actual !== expected)
            throw Error("Expected " + expected + "args; got " + actual);
        return _func.apply(this, arguments);
    };
}

...and use it like this...
var f = enforce_arg_length(function(x, y, z) {
    return x + y + z;
});