Q:

Proving an integral relation (isotropic function)

In Hansen-McDonald's book Theory of Simple Liquids the following relation is often used:
We want to evaluate the integral
$$\int_V f(\vec r_1, \vec r_2) d \vec r_1$$
We observe that if the function $f$ is isotropic, i.e.
$$f(\vec r_1, \vec r_2) = f(\mid \vec r_1- \vec r_2 \mid) $$
then
$$\int_V f(\vec r_1, \vec r_2) d \vec r_1 = \int_V f(\mid \vec r_1- \vec r_2 \mid) d \vec r_1 =  f(r) \ V $$
where
$$V= \int_V d \vec r$$
This makes sense to me, because if the function only depends on the distance I can choose to fix $\vec r_1$ everywhere in the volume (obtaining a volume term) and I will be left with $f(r)=f(\mid \vec r_1- \vec r_2 \mid)$.
But how can I prove the last relation in a rigorous way? I guess it must be some kind of change of variables, but I cannot figure out which one.
Update
This relation is used for example in equation (2.5.15):

(notice that $\rho = N/V$. Also, $g(r) \to 1$ for $r\to \infty$)
I also just found out that a similar relation, which we can write as
$$\int_V \int_V f(\mid \vec r_1-\vec r_2\mid) d\vec r_1 d\vec r_2 = V \int_V f(r) d\vec r$$
is used in equation (2.5.18-19), with the following explanation:

(notice that in this case $v(r) \to 0$ for $r \to \infty$)
It would be also nice to start by proving this in two dimensions, i.e. for
$$\int_I \int_I f(\mid x-y\mid) dx dy \ \ \text{and} \ \ \int_I f(\mid x-y\mid) dy$$
where $I$ is a closed interval, even if I'm starting to suspect (see John Barber's answer) that this result is not rigorous.

A:

I think something must be wrong here. Counterexample:
Suppose
$$
f\left(\vec{r}_1, \vec{r}_2\right) =
f\left(\left| \vec{r}_1 - \vec{r}_2\right|\right) =
\exp\left(-\frac{1}{2}\frac{{\left|\vec{r}_1 - \vec{r}_2\right|}^2}{\epsilon^2}\right)
$$
for some small $\epsilon$. Suppose the length scale of $V$ is much larger than $\epsilon$, and consider the quantity
$$
g\left(\vec{r}_2\right) = \int_V d\vec{r}_1\, f\left(\vec{r}_1, \vec{r}_2\right)\, .
$$
The integrand is a narrow Gaussian centered at $\vec{r}_2$. If $\vec{r}_2$ is more than several multiples of $\epsilon$ away from the boundary of $V$, then essentially all of the Gaussian is integrated over, and
$$
g\left(\vec{r}_2\right) \approx {\left(2\pi \epsilon^2\right)}^{d/2}\, ,
$$
where $d$ is the dimensionality of the space.
If $\vec{r}_2$ is on the boundary of $V$, then about half the Gaussian is integrated over, and we have
$$
g\left(\vec{r}_2\right) \approx \frac{1}{2}{\left(2\pi \epsilon^2\right)}^{d/2}\, .
$$
These bear no resemblance to (what appears to be) the asserted relationship
$$
g\left(\vec{r}_2\right) = V\, f\left( \left| \vec{r}_2 \right| \right)\, .
$$
What section of H&M does this appear in? I've got a copy of it around here somewhere. I'm wondering if perhaps the actual relationship might be
$$
\int_V d\vec{r}_1 \int_V d\vec{r}_2\, f\left(\vec{r}_1-\vec{r}_2\right)
 = V \int_V d\vec{r}_1\, f\left(\vec{r}_1\right)\, ,
$$
which should be perfectly valid so long as $f$ is sufficiently strongly peaked or localized. Since it's H&M, I would imagine that $f$ is something like $f(r) = \exp\left[-U(r)/k_B T\right]$ or $f(r) = 1 - \exp\left[-U(r)/k_B T\right]$, where $U$ is an intermolecular potential?
Response to Update:
The thing to keep in mind is that there are some assumptions implicit in H&M that are relevant here. These integral identities don't apply to just any radial function, but only to the sort relevant in molecular thermodynamics. This assumes that the function $f(\vec{r})$ varies on a molecular length scale $\epsilon$, and that the domain of integration $V$ is more like a macroscopic length scale. So we have a radical difference of scales here. Outside a length scale $\epsilon$, the function $f$ will typically be either zero or constant. Under these assumptions, some of these integral "identities" are approximately true.
I'm not going to get into H&M Equations (2.5.15) and (2.5.18) copied above. They depend on the precise definition of the two-particle distribution function, which is beyond the scope of a math.stackexchange post.
I do want to address the last part of your update. Define:
$$
g(y) = \int_I dx\,  f(x - y)\, .
$$
Here $I$ is an interval of length $L$, and we assume that $f$ is compactly supported (more or less) over an interval of length on the order of $\epsilon$, a small number. An example would be:
$$
f(x) = \exp\left(-\frac{1}{2}\frac{x^2}{\epsilon^2}\right)\, .
$$
By the same argument as above,
$$
g(y) = \mathrm{constant} \approx \int_{-\infty}^{+\infty} dx\,  f(x)
$$
unless $y$ is within a distance of about $\epsilon$ of one of the boundaries of $I$. Thus the assertion in the original post is actually wrong, even for H&M-type functions, and isn't what is being used in the equations from H&M.
However:
\begin{align}
\int_I dy\, g(y) &\approx \int_I dy \int_{-\infty}^{+\infty} dx\,  f(x) \\
&\approx L \int_I dx\, f(x) \;+\; \text{An error of order $\epsilon$}\, .
\end{align}
Here I've implicitly assumed that the domain $I$ is sufficiently "centered" that
$$
\int_{-\infty}^{+\infty} dx\,  f(x) \approx \int_I dx\,  f(x)\, .
$$
As long as $f$ falls off sufficiently rapidly (i.e. don't try this with particles mediated by a Coulomb potential!), we can ignore the error term, and the "double integral" identity should approximately hold.
Update to address Equation 2.5.15 above:
Theory of Simple Liquids can be found here on Google Books. The relevant page is 31.
I've gone over the steps leading to equation 2.5.15, and I don't think it makes sense as written. I'm convinced it's a typo. 2.5.15 doesn't seem to follow from 2.5.14. I think the argument of the integral in 2.5.15 is supposed to be:
$$
g^{(2)}_N(r' + r, r') = g^{(2)}_N\left(\left|r' + r - r'\right|\right) = g^{(2)}_N\left(\left|r\right|\right) = g(r)
$$
That makes much more sense to me, and leads to the desired result.


Q:

Is there SWT Combo Box with any Object as data and LabelProvider for display?

I'm searching for an implementation of a Combo Box in SWT that will allow me to set the the entries in it with a list of any Object, in a similar way to Trees and Tables.
Ideally I want the String when dropped down to be able to be different to the final String once selected. IE a drop down to select a person that shows their age next to their name in the list, but only their name when selected and placed in the box.
All I can find that exists are String based Combo Boxes with no way of describing different display options, so I guess i's going to have to build a new component if I want the thing to work, but I was hoping someone has already implemented such a thing (since I've seen this sort of functionality in some applications) and I just can't find it?
I hope to create something like this.

A:

The JFace ComboViewer seems to be what you want. It is backed by a ModelProvider which holds your Objects. A LabelProvider is used to display the text inside the combo.
Here is an excellent tutorial by Vogella.
Here is an example that does what you want. It basically saves the current combo selection if a boolean of the displayed objects:
public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final ComboViewer viewer = new ComboViewer(shell, SWT.READ_ONLY);

    viewer.setContentProvider(ArrayContentProvider.getInstance());

    /* if the current person is selected, show text */
    viewer.setLabelProvider(new LabelProvider() {
        @Override
        public String getText(Object element) {
            if (element instanceof Person) {
                Person current = (Person) element;

                if(current.isSelected())
                    return current.getName();
                else
                    return "";
            }
            return super.getText(element);
        }
    });

    final Person[] persons = new Person[] { new Person("Baz"),
            new Person("BazBaz"), new Person("BazBazBaz") };

    viewer.setInput(persons);

    /* within the selection event, tell the object it was selected */
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Person person = (Person)selection.getFirstElement();

            for(Person p : persons)
                p.setSelected(false);

            person.setSelected(true);

            viewer.refresh();
        }
    });

    viewer.setSelection(new StructuredSelection(viewer.getElementAt(0)), true);

    shell.pack();
    shell.setSize(200, shell.getSize().y);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

public static class Person {
    private String name;

    /* this will be true for the selected person */
    boolean isSelected;

    public Person(String name) {
        this.name = name;
        this.setSelected(false);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

}

A:

Many thanks to Baz for putting me on the right track and providing me with some initial code. But having taken all this in I wanted something cleaner to use in my RCP view itself and also though a generic instance of a combo box would be a nice to have in future, so I've wrapped all the boilerplate stuff in a new class that you can use like this:
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person("Baz",26));
    persons.add(new Person("Glen",27));
    persons.add(new Person("Jimmy",18));

    TypedComboBox<Person> box = new TypedComboBox<Person>(parent);

    box.addSelectionListener(new TypedComboBoxSelectionListener<Person>() {

        @Override
        public void selectionChanged(TypedComboBox<Person> typedComboBox,
                Person newSelection) {
            System.out.println(newSelection);
        }
    });

    box.setLabelProvider(new TypedComboBoxLabelProvider<Person>() {

        @Override
        public String getSelectedLabel(Person element) {
            return element.getName();
        }

        @Override
        public String getListLabel(Person element) {
            return element.getName() + " | " + element.getAge();
        }
    });

    box.setContent(persons);

    box.selectFirstItem();

For my view where I'm going to need multiple selection boxes with various objects I am much more happy using the typed box as I'm not casting stuff and reproducing boilerplate code in the body of the view's code.
You don't have to set a label provider if you just want the toSting() method used, otherwise there are two labels to provide, one for the selected item, and one for all the others.
Just in case anyone stumbles upon this question with the same issue as me here's my code, feedback would be greatly appreciated.
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class TypedComboBox<T> {

    private ComboViewer viewer;
    private TypedComboBoxLabelProvider<T> labelProvider;
    private List<T> content;
    private List<TypedComboBoxSelectionListener<T>> selectionListeners;
    private T currentSelection;

    public TypedComboBox(Composite parent) {
        this.viewer = new ComboViewer(parent, SWT.READ_ONLY);
        this.viewer.setContentProvider(ArrayContentProvider.getInstance());

        viewer.setLabelProvider(new LabelProvider() {
            @Override
            public String getText(Object element) {
                T typedElement = getTypedObject(element);
                if (labelProvider != null && typedElement != null) {
                    if (typedElement == currentSelection) {
                        return labelProvider.getSelectedLabel(typedElement);
                    } else {
                        return labelProvider.getListLabel(typedElement);
                    }

                } else {
                    return element.toString();
                }
            }
        });

        viewer.addSelectionChangedListener(new ISelectionChangedListener() {
            @Override
            public void selectionChanged(SelectionChangedEvent event) {
                IStructuredSelection selection = (IStructuredSelection) event
                        .getSelection();
                T typedSelection = getTypedObject(selection.getFirstElement());
                if (typedSelection != null) {
                    currentSelection = typedSelection;
                    viewer.refresh();
                    notifySelectionListeners(typedSelection);
                }

            }
        });

        this.content = new ArrayList<T>();
        this.selectionListeners = new ArrayList<TypedComboBoxSelectionListener<T>>();
    }

    public void setLabelProvider(TypedComboBoxLabelProvider<T> labelProvider) {
        this.labelProvider = labelProvider;
    }

    public void setContent(List<T> content) {
        this.content = content;
        this.viewer.setInput(content.toArray());
    }

    public T getSelection() {
        return currentSelection;
    }

    public void setSelection(T selection) {
        if (content.contains(selection)) {
            viewer.setSelection(new StructuredSelection(selection), true);
        }
    }

    public void selectFirstItem() {
        if (content.size()>0) {
            setSelection(content.get(0));
        }
    }
    public void addSelectionListener(TypedComboBoxSelectionListener<T> listener) {
        this.selectionListeners.add(listener);
    }

    public void removeSelectionListener(
            TypedComboBoxSelectionListener<T> listener) {
        this.selectionListeners.remove(listener);
    }

    private T getTypedObject(Object o) {
        if (content.contains(o)) {
            return content.get(content.indexOf(o));
        } else {
            return null;
        }
    }

    private void notifySelectionListeners(T newSelection) {
        for (TypedComboBoxSelectionListener<T> listener : selectionListeners) {
            listener.selectionChanged(this, newSelection);
        }
    }

And the label provider interface.
public interface TypedComboBoxLabelProvider<T> {

    public String getSelectedLabel(T element);

    public String getListLabel(T element);

}

And the selection listener:
public interface TypedComboBoxSelectionListener<T> {

    public void selectionChanged(TypedComboBox<T> typedComboBox, T newSelection);
}


Q:

Afinal para que serve a função repr no python?

Sou meio novato em python e queria saber para que realmente serve essa função tão confusa, procurei em varios sites porém nenhum tem realmente dizendo para que serve ela

A:

__repr()__ serve para representar um objeto como uma string. Não precisa ser chamado diretamente. Toda vez que o Python precisa resolver um objeto como string, __repr__() será chamado automaticamente.
Vários tipos de objetos implementam __repr__() por padrão. Para objetos, normalmente __repr__() devolve a descrição e a referência em memória para o objeto.
A grande vantagem de __repr__() é justamente poder reescrevê-lo, como fiz aqui. Ao invés de escrever o objeto como <tipo + referência>, você pode formatar sua string da maneira como bem entender:
class MeuObjeto(object):
    def __init__(self):
        self.valor1 = 1
        self.valor2 = "2"

    def __repr__(self):
        return str(self.valor1) + ", " + self.valor2

Teste:
>>> o = MeuObjeto()
>>> o
1, 2

A:

O repr chama o método interno __repr__ do objeto. A ideia dele é retornar uma representação como string de qualquer objeto - mas pensando antes no programador do que no usuário final do programa. Sobretudo é o repr que é chamado para cada resultado de expressão quando usamos o Python no modo interativo.
Assim, por exemplo, para uma string numa variável a, repr(a) retorna a string, mas com aspas simples em volta. Em contraste, str(a) mostra o objeto como string, mas numa forma que seja amigável de ser mostrada para o usuário, quando o programa estiver em execução. (Ou seja, o conteúdo da string, sem as aspas). Veja a diferença:
>>> a = "maçã"
>>> a  # internamente, o Python chama o "a.__repr__"
'maçã'
>>> print(a) # internamente, o Python (o código no "print") chama "a.__str__"
maçã

Via de regra, para objetos simples, built-in, havia a idaia de que se você copiasse a saída do repr e colasse como texto num terminal Python ou programa, você recriaria o objeto inicial de volta. Isso vale para strings, listas, dicionários, tuplas e sets - e você pode criar reprs de seus próprios objetos de forma que também valha pra eles. Mas o __repr__ padrão mostra o nome da classe e o ID da instância (que no Python é igual o endereço de memória do objeto, mas isso é um detalhe de implementação): ou seja, não é possível recriar o objeto "repr"esentado por padrão, mas pode-se distinguir uma instância de outra olhando-se os seus reprs no terminal.
Diferença entre __repr__ e  repr
Por fim, vale notar que todo objeto em Python tem um método __repr__ - por que o o object, raiz de todos os objetos em Python tem um - e esse método é chamado automaticamente em várias situações: para ter uma forma de texto de um objeto para uma sessão interativa de Python, uma representação de texto a ser incluída de forma recursiva numa representação de texto de outro objeto, que contenha o objeto inicial, e algumas outras.
Já o método "built-in" repr é a forma de se chamar explicitamente os __repr__ de um objeto quando queremos fazer isso. Assim como o len pode chamar o método __len__ e também para hash e __hash__, next e __next__ - a idéia é que essas funções built-in funcionem praticamente como operadores unários para acessar essas funcionalidades que os objetos tem e que são escritas na forma de métodos com os "nomes mágicos", com dois underscores. (Em textos não oficiais - como e-mails, cursos, e tutorais, você vai ver esses métodos sendo chamados de métodos "dunder" - uma contração de "double-underscore".)
E por fim, vale dizer que quando é solicitada a representação como string de um objeto, com str, o Python busca primeiro o método __str__ - mas ao contrário do __repr__ nem todos os objetos tem um método __str__padrão. (A classe object não implementa __str__) então a função built-n str ao não encontrar o  __str__ chama o __repr__ do objeto para ter sua representação como string.  Esse é um dos motivos de ser preferível chamar os métodos built-in a chamar os métodos "dunder" diretamente - mesmo que para o repr não haja quase nenhuma diferença entre fazer uma coisa e outra.
Em Python2 tinhamos agravantes do tipo: o método __repr__ sempre tinha que retornar uma string, não um texto unicode. E os objetos, além do método __str__ podiam implementar também o __unicode__. Ademais, o repr de strings transformavam qualquer caractere não ASCII em uma sequência de escape do tipo "\0xPython 3 simplificou bastante tudo isso.


Q:

Don't display icon on MenuBar in Android

I'm building an app with AndroidStudio. I want to display an ActionBar in my application.
I want to add a menu into my AppCompactActivity. This is the menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_save"
        android:showAsAction="always"
        android:title="Salva"/>
</menu>

This is the layout that I can see from Android Studio preview.

This is my AppCompactActivity:
public class setting extends AppCompatActivity{
    public Program program;
    public TextView textTargetUri;
    public TextView labelUrl;
    public ImageView targetImage;
    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        img = (ImageView)findViewById(R.id.ImageView01);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_setting, menu);
        return super.onCreateOptionsMenu(menu);
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.action_search:
            getSchermataHome();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

But this is the layou that I can see:

How can I fixed it?

A:

Try using the following code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_save"
    android:title="Salva"
    app:showAsAction="ifRoom|always"/>
</menu>

change always to ifRoom|always with app attribute


Q:

React render string as HTML in ant design

I'm using ant design dropdown. I have dynamic data from API and when I try to render those data into dropdown menu, It is rending as string.
So I used this react-html-parser library to render string as HTML but it does not work.
renderSocialMedia = () => {
if (this.props.weblookup) {
  let socialmedialookup = this.props.weblookup
  webitems = ""
  return socialmedialookup.map((k, index) => {
    if (k.name.toLowerCase() != "other")
      return webitems = "<Menu.Item key=" + k.id + ">" + k.name + "</Menu.Item>"
  })
 }
}

{ReactHtmlParser(webitems)}

<FormItem>
 {getFieldDecorator('AddNetwork', {
  initialValue: "",
 })(
 <Dropdown overlay={
  <Menu onClick='{this.handleMenuClick}'>

{ReactHtmlParser(webitems)}

  </Menu>
} trigger={['click']}>

  Add Username
  <Icon type="down" />

</Dropdown>
)}

OUTPUT:

A:

As you're using React you must properly format a DOM element. So, Try this,
return webitems = <Menu.Item key={ k.id }>{ k.name}</Menu.Item>

Hope it helps. Happy Coding!!


Q:

How can I use `defineProperty` to create a readonly array property?

I have the following as a part of a module (names simplified for purpose of question):
In "module.js":
var _arr;

_arr = [];

function ClassName () {
    var props = {};

    // ... other properties ...

    props.arr = {
        enumerable: true,
        get: function () {
            return _arr;
        }
    };

    Object.defineProperties(this, props);

    Object.seal(this);
};

ClassName.prototype.addArrValue = function addArrValue(value) {

    // ... some code here to validate `value` ...

    _arr.push(value);
}

In "otherfile.js":
var x = new ClassName();

With the implementation above, and the sample code below, adding values to arr can be achieved in two ways.
// No thank you.
x.arr.push("newValue"); // x.arr = ["newValue"];

// Yes please!
x.addArrValue("newValue"); // Only this route is desired.

Does anyone know how to achieve a readonly array property?
Note: writeable is false by default and no difference is observed if I explicitly set it.

A:

Object.freeze() will do what you're asking (on browsers properly implementing the spec).  Attempts to modify the array will either fail silently or throw TypeError when in strict mode.
The easiest solution is to return a new frozen copy (freeze is destructive):
return Object.freeze(_arr.slice());

However, if more reading than writing is expected, lazy-cache the most recently accessed frozen copy and purge upon write (since addArrValue controls writes)
Lazy caching read-only copy using modified original example:
"use strict";
const mutable = [];
let cache;

function ClassName () {
    const props = {};

    // ... other properties ...

    props.arr = {
        enumerable: true,
        get: function () {
            return cache || (cache = Object.freeze(mutable.slice());
        }
    };

    Object.defineProperties(this, props);

    Object.seal(this);
};

ClassName.prototype.addArrValue = function addArrValue(value) {

    // ... some code here to validate `value` ...

    mutable.push(value);
    cache = undefined;
}

Lazy caching read-only copy using ES2015 classes:
class ClassName {
    constructor() {
        this.mutable = [];
        this.cache = undefined;
        Object.seal(this);
    }

    get arr() {
        return this.cache || (this.cache = Object.freeze(this.mutable.slice());
    }

    function addArrValue(value) {
        this.mutable.push(value);
        this.cache = undefined;
    }
}

A "transparent" re-usable class hack (rarely required):
class ReadOnlyArray extends Array {
    constructor(mutable) {
        // `this` is now a frozen mutable.slice() and NOT a ReadOnlyArray
        return Object.freeze(mutable.slice());
    }
}

const array1 = ['a', 'b', 'c'];
const array2 = new ReadOnlyArray(array1);

console.log(array1); // Array ["a", "b", "c"]
console.log(array2); // Array ["a", "b", "c"]
array1.push("d");
console.log(array1); // Array ["a", "b", "c", "d"]
console.log(array2); // Array ["a", "b", "c"]
//array2.push("e"); // throws

console.log(array2.constructor.name); // "Array"
console.log(Array.isArray(array2));   // true
console.log(array2 instanceof Array); // true
console.log(array2 instanceof ReadOnlyArray); // false

A proper re-usable class:
class ReadOnlyArray extends Array {
    constructor(mutable) {
        super(0);
        this.push(...mutable);
        Object.freeze(this);
    }
    static get [Symbol.species]() { return Array; }
}

const array1 = ['a', 'b', 'c'];
const array2 = new ReadOnlyArray(array1);

console.log(array1); // Array ["a", "b", "c"]
console.log(array2); // Array ["a", "b", "c"]
array1.push("d");
console.log(array1); // Array ["a", "b", "c", "d"]
console.log(array2); // Array ["a", "b", "c"]
//array2.push("e"); // throws

console.log(array2.constructor.name); // "ReadOnlyArray"
console.log(Array.isArray(array2));   // true
console.log(array2 instanceof Array); // true
console.log(array2 instanceof ReadOnlyArray); // true


Q:

Automatically resize width of DataGridCoulmn/AdvancedDataGridColumn to fit content

I want that the DataGridColumn or AdvancedDataGridColumn would automatically resize it's width so as to fit the content within..
I'm new to flex. I want to implement something like HTML tables.
The Data Rendered is simple Text. Some Rows have little longer Text, in that case I would like to automatically extend the width of DataGridColumn.
Any help to solve this.
Thanks in advance

A:

You've hit upon one of the biggest problems of the DataGrid and AdvancedDataGrid. I absolutely hate how hard it is to get cell content to appear comfortably. For reasons not immediately apparent, narrow field values will appear in very wide cells while wide content and headers will get scrunched.
This is especially true for the first and last columns for some reason.
The only solution I have found is to set the minWidth property on columns, and I have to go through the data first to find the widest outliers in those columns and make sure they fit comfortably. Another solution that helps is to have dummy columns on the left and right that are given widths and minWidths and maxWidths of some very small size, say 5, which seems to allow the real columns in the middle to "breathe" a little better.
<mx:columns>
  <mx:DataGridColumn id="leftDummy" width="5" minWidth="5" maxWidth="5"/>
  <!-- Your "real" columns here, with minWidth assignments -->
  <mx:DataGridColumn id="rightDummy" width="5" minWidth="5" maxWidth="5"/>
</mxcolumns>

Be careful, though. If you set a width on a column it gets interpreted not as a literal value or an actual percentage but as some kind of half-assed proportion. I can only assume that the column-sizing procedures get tired of calculating and settle on some kind of "reasonable" interpretation of column width — which, of course, turns out to be utterly unreasonable much of the time.
At this moment I am so frustrated I am considering going with a 3rd party product, ElfGrid, which solves these issues and more. Look at the documentation, especially the ElfColumnUtils, which have some very handy methods for dealing with these issues. It's also quite fast in the testing I've done.


Q:

Regular expression to match particular starting word or nothing

I'm struggling to come up with the correct regex for the following scenario.
Let's say you have to match a word either starts with http- or nothing
eg : http-test-data, test-data should be a match but xyz-test-data shouldn't be a match
the regex i came up so far is
(?:http-)?(test-data)
but it matches xyz-test-data as well.

A:

You could simply use the following:
(?:http-|^)(test-data)

This tests for either a positive look-behind of http- or for the beginning of the string before test-data.
For example, for the sample data as follows:
http-test-data
xyz-test-data
http-test-data
xyz-test-data
test-data
yes-yes-test-data
-test-data

It yeilds:
http-test-data
http-test-data
test-data


Q:

My routes.rb file doesn't redirect me to /

I have created a NEW rails application using
rails new rail_app
So if I want to see my development site I need to do the following
http://localhost:3000/Site/index
I want to reroute all requests to http://localhost:3000
The book I'm using to learn from is an older version of rails and it tells me to uncomment
map.connect '', :controller => 'site', :action => 'index'
but it doesn't seem to work. Any help would be appreciated.

A:

You need to direct a controller action to root using the root command. See this guide:
http://guides.rubyonrails.org/routing.html#using-root


Q:

Parse Script Tag after BeautySoup in Python

Hello all members of the forum.
When parsing a page, I encountered the problem of extracting data from the tag script. The internal content of the tag is not an json object. Using web.driver results did not.
Who faced such things? I ask for your help.
Code example:

<script>window.ShopifyAnalytics = window.ShopifyAnalytics || {};
window.ShopifyAnalytics.meta = window.ShopifyAnalytics.meta || {};
window.ShopifyAnalytics.meta.currency = 'AUD';
var meta = {"product":{"id":8993669708,"vendor":"Womanizer","type":"Vibrators","variants":[{"id":31066737740,"price":14999,"name":"Womanizer - Black","public_title":"Black","sku":"172145678"},{"id":31066737804,"price":14999,"name":"Womanizer - Purple","public_title":"Purple","sku":"172146924"},{"id":31066737868,"price":14999,"name":"Womanizer - Pink","public_title":"Pink","sku":"172150324"},{"id":31066737996,"price":14999,"name":"Womanizer - Tattoo","public_title":"Tattoo","sku":"172205168"},{"id":1509908217881,"price":14999,"name":"Womanizer - Blue","public_title":"Blue","sku":"1725205076"}]},"page":{"pageType":"product","resourceType":"product","resourceId":8993669708}};
for (var attr in meta) {
  window.ShopifyAnalytics.meta[attr] = meta[attr];
}</script>

A:

Using Regex.
Demo:
from bs4 import BeautifulSoup
import json
import re

s = """<script>window.ShopifyAnalytics = window.ShopifyAnalytics || {};
window.ShopifyAnalytics.meta = window.ShopifyAnalytics.meta || {};
window.ShopifyAnalytics.meta.currency = 'AUD';
var meta = {"product":{"id":8993669708,"vendor":"Womanizer","type":"Vibrators","variants":[{"id":31066737740,"price":14999,"name":"Womanizer - Black","public_title":"Black","sku":"172145678"},{"id":31066737804,"price":14999,"name":"Womanizer - Purple","public_title":"Purple","sku":"172146924"},{"id":31066737868,"price":14999,"name":"Womanizer - Pink","public_title":"Pink","sku":"172150324"},{"id":31066737996,"price":14999,"name":"Womanizer - Tattoo","public_title":"Tattoo","sku":"172205168"},{"id":1509908217881,"price":14999,"name":"Womanizer - Blue","public_title":"Blue","sku":"1725205076"}]},"page":{"pageType":"product","resourceType":"product","resourceId":8993669708}};
for (var attr in meta) {
  window.ShopifyAnalytics.meta[attr] = meta[attr];
}</script>"""

soup = BeautifulSoup(s, "html.parser")
scr = soup.find("script")
m = re.search(r"var meta = (.*?);", scr.string)
if m:
    data = json.loads(m.group(1))
    for sku in data["product"]["variants"]:
        print(sku["sku"])

Output:
172145678
172146924
172150324
172205168
1725205076


Q:

Is it possible to send email from observer using SMTP

Is it possible to send email to customer when he place an order
this is my event.xml
<?xml version='1.0'?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='urn:magento:framework/Event/etc/events.xsd'>
   <event name='checkout_onepage_controller_success_action'>
        <observer
                name='Pulsestorm_HelloWorldMVVM_HelloWorld'
                instance='Pulsestorm\HelloWorldMVVM\Observer\HelloWorld'
        />
    </event>
</config>

and this is my observer
<?php

namespace Pulsestorm\HelloWorldMVVM\Observer;

use Magento\Framework\Event\ObserverInterface;

class HelloWorld implements ObserverInterface
{
    /**
     * @var ObjectManagerInterface
     */
    protected $_objectManager;
    protected $_orderRepositoryInterface;

    /**
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepositoryInterface
    ) {
        $this->_objectManager = $objectManager;
        $this->_orderRepositoryInterface = $orderRepositoryInterface;
    }

    /**
     * customer register event handler
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {

    $orderIds = $observer->getEvent()->getOrderIds();
    $order = $this->_orderRepositoryInterface->get($orderIds[0]);
    $items =$order->getAllVisibleItems();
    $productIds = array();
    foreach($items as $item) {
        $productIds[]= $item->getProductId();
    }

    //custoemr id
    $customerEmail = $order->getCustomerEmail();

   }

}

In $customerEmail i got customer mail id after that i have no idea how to send email using SMTP

A:

I hope you already configure smtp. if not please refer this link for send mail using your smtp.
key code of sending mail
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
class ClassName implements ObserverInterface
{
protected $storeManager;
protected $_transportBuilder;
protected $inlineTranslation;
public function __construct(StoreManagerInterface $smi,TransportBuilder $tb,StateInterface $si)
{
    $this->storeManager=$smi;
    $this->_transportBuilder=$tb;
    $this->inlineTranslation=$si;
}
public function yourFunctionName()
{
       $templateOptions = array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getId());
        $templateVars = array(
            'store' => $this->storeManager->getStore(),
            'customer_name' => $cname,
            'message'   => 'We processed your order ID '.$orederid.'. We will contact you soon in mail for the acknowledgement if you not receive mail within 4 hours please get help from support@xxx.com'
        );
        $from = array('email' => "xxxxx@xxx.xxx", 'name' => 'AnyName');
        $this->inlineTranslation->suspend();
        $to = array('xxxxx@xxx.xxx');
        $transport = $this->_transportBuilder->setTemplateIdentifier('order_template')
            ->setTemplateOptions($templateOptions)
            ->setTemplateVars($templateVars)
            ->setFrom($from)
            ->addTo($to)
            ->getTransport();
        $transport->sendMessage();
        $this->inlineTranslation->resume();
   }
}

please note it setTemplateIdentifier('order_template') so you need to create order_template. for create email template refer this link


Q:

How to encrypt large data with travis for Node environment

I'm trying to add NODE variable to travis through travis encrypt feature. However, the text is too large that I cannot run it.
travis encrypt super=large-text --add

I tried to look into the instruction through Travis Encryption Files. However, it doesn't show the content of the encrypt file. I'm not sure how to encrypt a large variable to travis. Please help to take a look at this. Thanks

A:

Just go to Travis CI Dashboard and add your secret variables.


Q:

Convert comma delimited string to list

I have the following powershell code:
$Credentials = 'Credentials: myacct1,myacct2'

$runtimes = $Credentials -match "Credentials: (?<content>.*)"
$runtimeList = $matches['content']
Foreach ($runtime in $runtimeList)
{
    Write-Host $runtime
}

That simply returns myacct1,myacct2 where I want it to iterate through the list
myacct1
myacct2

A:

I'm pretty sure you just need to split the matched string by , using String.Split().
$Credentials = 'Credentials: myacct1,myacct2'

$runtimes = $Credentials -match "Credentials: (?<content>.*)"
$runtimeList = $matches['content'].Split(",")
Foreach ($runtime in $runtimeList)
{
    Write-Host $runtime
}

# Output:
# myacct1
# myacct2


Q:

É possível converter um array [Any] para NSData?

Preciso gerar uma variável NSData a partir de um array que permite qualquer tipo de dado.
Tentei o seguinte cógigo, que não funcionou:
let a0 : Int8 = 3
let a1 : UInt16 = 231
let a2 : Int = 1024

let array : [Any] = [a2, a1, a0]
var data = NSData(bytes: array, length: array.count)

Ele me retorna o seguinte:

array: [1024, 231, 3]
data: <000400>

Quando eu tento converter um array de um tipo de dados apenas, a conversão ocorre sem problemas.
let arrayUInt8 : [UInt8] = [255, 0x02, 3]

let dataUInt8 = NSData(bytes: arrayUInt8, length: arrayUInt8.count)

Me retorna o seguinte:

arrayUInt8: [255, 2, 3]
dataUInt8: < ff0203>

Desde já agradeço.

A:

Voce primeiro deveria extender IntegerType pra poder extrair os seus bytes em forma de NSData usando getBytes e usa sizeof() do dynamicType pra determinar a lenght do byte:
extension IntegerType {
    var data: NSData {
        var source = self
        return NSData(bytes: &source, length: sizeof(self.dynamicType))
    }
}

Com isso feito voce deve criar um método pra concatenar os seus dados antes de enviar:
func getDataToSend(first: Int8,_ second: UInt16,_ third: Int) -> NSData {
    let mutableData = NSMutableData()
    mutableData.appendData(first.data)
    mutableData.appendData(second.data)
    mutableData.appendData(third.data)
    return mutableData
}

E voce também pode extender NSData pra facilitar voce a extrair os seus elementos dela:
extension NSData {
    var getElements:(first: Int8, second: UInt16, third: Int) {
        var resultInt8: Int8 = 0
        var resultUInt16: UInt16 = 0
        var resultInt: Int = 0
        getBytes(&resultInt8, range: NSRange(location: 0, length: sizeof(Int8)))
        getBytes(&resultUInt16, range: NSRange(location: 1, length: sizeof(UInt16)))
        getBytes(&resultInt, range: NSRange(location: 3, length: sizeof(Int)))
        return (resultInt8, resultUInt16, resultInt)
    }
}

Testando:
let a0: Int8 = 3
let a1: UInt16 = 231
let a2: Int = 1024

let dataToSend = getDataToSend(a0, a1, a2)
print(dataToSend.length) // 11

let elementsFromData = dataToSend.getElements   // (.0 3, .1 231, .2 1024)
let firstElement = elementsFromData.first       // 3
let secondElement = elementsFromData.second     // 231
let thirdElement = elementsFromData.third       // 1024


Q:

Identify why a user can drop a database

I have a sql server user that has the ability to drop any database. I've been running the code below to check the rights that the user has in SQL Server but have not been able to identify how the user has the ability to drop databases.  Is there a sql script that can help me identify how this user can drop dbs?  Is there a command to deny them dropping any databases?  (SSMS is not showing the user as part of the dbcreator role)
select USER_NAME(p.grantee_principal_id) AS principal_name,
    dp.type_desc AS principal_type_desc,
    p.class_desc,
    OBJECT_NAME(p.major_id) AS object_name,
    p.permission_name,
    p.state_desc AS permission_state_desc
from    sys.database_permissions p
inner   JOIN sys.database_principals dp
on     p.grantee_principal_id = dp.principal_id
order by principal_name

The output of the query above provides the following three records for the user if it is helpful

class_desc    object_name permission_name permission_state_desc
  OBJECT_OR_COLUMN  xp_cmdshell EXECUTE          GRANT
  DATABASE          NULL           CONNECT             GRANT
  DATABASE             NULL           CREATE DATABASE GRANT

A:

I would suggest running this query on the master
SELECT
    [UserName] = CASE princ.[type]
                    WHEN 'S' THEN princ.[name]
                    WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
                 END,
    [UserType] = CASE princ.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                 END,
    [DatabaseUserName] = princ.[name],
    [Role] = null,
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM
    --database user
    sys.database_principals princ
LEFT JOIN
    --Login accounts
    sys.login_token ulogin on princ.[sid] = ulogin.[sid]
LEFT JOIN
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col ON col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE
    princ.[type] in ('S','U')
UNION
--List all access provisioned to a sql user or windows user/group through a database or application role
SELECT
    [UserName] = CASE memberprinc.[type]
                    WHEN 'S' THEN memberprinc.[name]
                    WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
                 END,
    [UserType] = CASE memberprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                 END,
    [DatabaseUserName] = memberprinc.[name],
    [Role] = roleprinc.[name],
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM
    --Role/member associations
    sys.database_role_members members
JOIN
    --Roles
    sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
JOIN
    --Role members (database users)
    sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id]
LEFT JOIN
    --Login accounts
    sys.login_token ulogin on memberprinc.[sid] = ulogin.[sid]
LEFT JOIN
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
UNION
--List all access provisioned to the public role, which everyone gets by default
SELECT
    [UserName] = '{All Users}',
    [UserType] = '{All Users}',
    [DatabaseUserName] = '{All Users}',
    [Role] = roleprinc.[name],
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM
    --Roles
    sys.database_principals roleprinc
LEFT JOIN
    --Role permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
JOIN
    --All objects
    sys.objects obj ON obj.[object_id] = perm.[major_id]
WHERE
    --Only roles
    roleprinc.[type] = 'R' AND
    --Only public role
    roleprinc.[name] = 'public' AND
    --Only objects of ours, not the MS objects
    obj.is_ms_shipped = 0
ORDER BY
    princ.[Name],
    OBJECT_NAME(perm.major_id),
    col.[name],
    perm.[permission_name],
    perm.[state_desc],
    obj.type_desc--perm.[class_desc]

This should give you a pretty good idea of the roles that have access to your master database and see weather or not the user has any of those roles. You can also run this against any of your other databases to check the user's permissions on a database by database level. This should be an important tool to help track this down.

A:

Is there a sql script that can help me identify how this user can drop dbs?

I have used this a few times with some good results, source of the code below can be found here:

SELECT SP1.[name] AS 'Login', 'Role: ' + SP2.[name] COLLATE DATABASE_DEFAULT AS 'ServerPermission'
FROM sys.server_principals SP1
  JOIN sys.server_role_members SRM
    ON SP1.principal_id = SRM.member_principal_id
  JOIN sys.server_principals SP2
    ON SRM.role_principal_id = SP2.principal_id
UNION ALL
SELECT SP.[name] AS 'Login' , SPerm.state_desc + ' ' + SPerm.permission_name COLLATE DATABASE_DEFAULT AS 'ServerPermission'  FROM sys.server_principals SP
  JOIN sys.server_permissions SPerm
    ON SP.principal_id = SPerm.grantee_principal_id
ORDER BY [Login], [ServerPermission];

Is there a command to deny them dropping any databases?

Going on documentation here, the security requirements for a user to drop a database are stated as:

Requires the CONTROL permission on the database, or ALTER ANY DATABASE permission, or membership in the db_owner fixed database role

You can explictily deny the permission to one mentioned above but understand that the level you deny it at may not take affect like you think. I recall reading a white paper that walked through how SQL Server goes about validating permissions of a user upon connection but cannot locate it right now. If I recall I may deny them connection to a database but the fact the user is part of the sysadmin role takes precedence.
I would look at auditing specifically for the DROP DATABASE command to be safe.

A:

The query you've got there will list only permissions for the database against which you run it.  One way to get permission to drop a database is ALTER ANY DATABASE, which is a server-level permission.  To check those, try this query:
SELECT
  [srvprin].[name] [server_principal],
  [srvprin].[type_desc] [principal_type],
  [srvperm].[permission_name],
  [srvperm].[state_desc]
FROM [sys].[server_permissions] srvperm
  INNER JOIN [sys].[server_principals] srvprin
    ON [srvperm].[grantee_principal_id] = [srvprin].[principal_id]
WHERE [srvprin].[type] IN ('S', 'U', 'G')
ORDER BY [server_principal], [permission_name];

In other words, the user might be getting the permission to drop databases at the server login level rather than the database user level.


Q:

What genre of video game does Diablo belong to?

I've recently played Diablo 1 and 2 and I'm totally hooked. Now I've been wondering what genre this game belongs to, so it would help me find similar games.

A:

The genre has a few popular names, including:

Hack and slash
Action RPG
Dungeon crawl
Diablo-like or Diablo-esque

And sometimes even the term "roguelike" is used - there is a vast difference between the roguelike genre and games like Diablo, but the latter are obviously influenced by the former.
The most common term I've encountered is "hack and slash". There are many, many games that belong to this genre, especially since the success of Diablo.
The excellent Moby Games site has a page about the genre, which briefly outlines what defines it as well as providing a list of all the games it considers to be "Diablo variants".


Q:

How to set value of multiple input fields with same button

I want to set input field value only when it is clicked and want to set value in two different input fields from same button, when one input field is selected only set value in this field when other selected/clicked value set their.
Try with different ways but not successful.
I hope i will be helped in this problem.
thanks

var phoneScreen = $("#phone"); var phoneNumber = phoneScreen.val();
var delBtn = $("#del"); var clrBtn = $("#clr");
var numBtn = $(".number");

numBtn.click(function() {
    var number = $(this).val();
  updatePhoneNumber(number);
  printPhoneNumber();
});
delBtn.click(function() {
    deleteNumber();
  printPhoneNumber();
});
clrBtn.click(function() {
    clearNumber();
  printPhoneNumber();
});

function updatePhoneNumber(newNumber) {
    phoneNumber = phoneNumber + newNumber;
}
function deleteNumber() {
    phoneNumber = phoneNumber.slice(0,-1);
}
function clearNumber() {
    phoneNumber = "";
}
function printPhoneNumber() {
    phoneScreen.val(phoneNumber);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

<input type="number" id="phone" placeholder="(123) 45-7" min="0" step="1"/>

<input type="number" id="phone2" placeholder="(123) 45-7" min="0" step="1"/>

<form action="#" method="post" id="form">
<button type="button" class="rightside__pad-btn number" value="1">1</button>
<button type="button" type="button" class="rightside__pad-btn number" value="2">2</button>
<button type="button" type="button" class="rightside__pad-btn number" value="3">3</button>

<button type="button" type="button" class="rightside__pad-btn number" value="4">4</button>
<button type="button" type="button" class="rightside__pad-btn number" value="5">5</button>
<button type="button" type="button" class="rightside__pad-btn number" value="6">6</button>

<button type="button" type="button" class="rightside__pad-btn number" value="7">7</button>
<button type="button" type="button" class="rightside__pad-btn number" value="8">8</button>
<button type="button" type="button" class="rightside__pad-btn number" value="9">9</button>

<button type="button" id="del" class="rightside__pad-btn del">
</button>
<button type="button" class="rightside__pad-btn number" value="0">0</button>
<button type="button" id="dial" class="rightside__pad-btn" value="">
</button>

    </form>

A:

I just added few changes

var hasFocus = $('#phone'); Set #phone as default focused element.
Update the hasFocus to selected input element.

   $('input[type=number]').on('click', function(){
      hasFocus = $(this);
    });

Now added function to set value to focused element hasFocus.val(hasFocus.val() +number);
Please update

var phoneScreen = $("#phone");
var phoneNumber = phoneScreen.val();
var delBtn = $("#del"); var clrBtn = $("#clr");
var numBtn = $(".number");
var hasFocus = $('#phone');
$('input[type=number]').on('click', function(){
  hasFocus = $(this);
})
numBtn.click(function() {
    var number = $(this).val();
    hasFocus.val(hasFocus.val() +number);
  //updatePhoneNumber(number);
  //printPhoneNumber(number);
});
delBtn.click(function() {
    deleteNumber();
  printPhoneNumber();
});
clrBtn.click(function() {
    clearNumber();
  printPhoneNumber();
});

function updatePhoneNumber(newNumber) {
    phoneNumber = phoneNumber + newNumber;
}
function deleteNumber() {
    phoneNumber = phoneNumber.slice(0,-1);
}
function clearNumber() {
    phoneNumber = "";
}
function printPhoneNumber() {
    phoneScreen.val(phoneNumber);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

<input type="number" id="phone" placeholder="(123) 45-7" min="0" step="1"/>

<input type="number" id="phone2" placeholder="(123) 45-7" min="0" step="1"/>

<form action="#" method="post" id="form">
<button type="button" class="rightside__pad-btn number" value="1">1</button>
<button type="button" type="button" class="rightside__pad-btn number" value="2">2</button>
<button type="button" type="button" class="rightside__pad-btn number" value="3">3</button>

<button type="button" type="button" class="rightside__pad-btn number" value="4">4</button>
<button type="button" type="button" class="rightside__pad-btn number" value="5">5</button>
<button type="button" type="button" class="rightside__pad-btn number" value="6">6</button>

<button type="button" type="button" class="rightside__pad-btn number" value="7">7</button>
<button type="button" type="button" class="rightside__pad-btn number" value="8">8</button>
<button type="button" type="button" class="rightside__pad-btn number" value="9">9</button>

<button type="button" id="del" class="rightside__pad-btn del">
</button>
<button type="button" class="rightside__pad-btn number" value="0">0</button>
<button type="button" id="dial" class="rightside__pad-btn" value="">
</button>

    </form>


Q:

Regex to match linebreaks not preceded by non-escaped quotes in text file

I have a textfile where strings are enclosed by quotes " " and any containing quotes are escaped by \. I wan't to remove any linebrakes (\n) at in the text, as long as they are not preceded by an un-escaped quote sign ("), since thats the end of a line.
Here's an example:
"tre miljarder på att modernisera snabbtågen.\"
Dagens mest ironiska nyhet.,Väntar på att alla Summerburst-uppdateringar snart ska dö ut   så min ångest kan släppa och jag kan återgå till ett normalt liv.,RT @mapeone: En till hashtag     på Facebook och jag badar naken i grisblod.,Dagens biologiska lektion och psykologiska  reflektion.
Så förlorade fåglarna sina penisar - DN.SE http://t.co/PFaseQMt8B,Hahaha \"@Aliceyouknow:  Hah ironiskt att jag för exakt ett år sen ville gräva ner mig lika mycket som jag vill nu   med.\" #livet,Det är bara kvinnor som på riktigt förstår paniken i om Zlatans hår skulle    försvinna. #ikon,@nellie_lind ah han har ju rakat sidorna, snart ryker väl hela skiten,Alltså    Zlatan ge fan i att mecka med håret.,Jag har ett jobb. Hur tungt är inte det. #tungt"

The regex pattern I've come up with so far looks like this:
[^"]\n+

But it also matches the character before the \n, e.g. the quote at the end of "snabbtågen.\" on line 1 and dot (.) after "reflektion" on line 2.
I want it to match a \n preceded by anything else than a non escaped ", but not include what's preceding it. How can that be done?

A:

You should use negative lookbehind assertion
>>> print s
'first line'
'hello world
again'
>>> s2 = re.sub(r"(?<!')\s+", " ", s)
>>> print s2
'first line'
'hello world again'


Q:

RTFMP - Remote stream not showing

I'm trying to create a 2-way videochat. Your own webcam shows perfectly fine, but the other doesn't. I used this page as an example: http://www.adobe.com/devnet/flashmediaserver/articles/p2p_apps_cirrus_lccs.html
Following the steps on the page doesn't seem to work for me. I exchange the peer IDs via PHP. I make my Flash visit a page, which stores the peer ID in the database using a POST request. To fetch the peer ID of the partner, I use PHP sessions, which store both your ID, and that of your partner. I can then use these variables to visit another PHP page, which echoes the partner's peer ID. Both are the same as in the database, so there's nothing wrong with that.
The NetConnection:
Connection = new NetConnection();
Connection.addEventListener(NetStatusEvent.NET_STATUS, CheckConnect);
Connection.connect(RTFMP + DevKey);

This is how I set up your own webcam plus its NetStream:
StreamOut = new NetStream(Connection, NetStream.DIRECT_CONNECTIONS);
var SelfCam:DynamicStreamingVideoSource = new DynamicStreamingVideoSource();
var VideoItems:Vector.<DynamicStreamingVideoItem>;
VideoItems = new Vector.<DynamicStreamingVideoItem>();
VideoItems[0] = new DynamicStreamingVideoItem();

SelfCam.host = "";
SelfCam.streamType = StreamType.LIVE;
SelfCam.streamItems = VideoItems;

Self.source = SelfCam;

var Cam:Camera = Camera.getCamera();
var Mic:Microphone = Microphone.getMicrophone();
Cam.setMode(380, 255, 15);
Cam.setQuality(0, 80);
Self.videoObject.attachCamera(Cam);

StreamOut.attachAudio(Mic);
StreamOut.attachCamera(Cam);
StreamOut.publish("vids");

And this is how I receive the published stream "vids":
StreamIn = new NetStream(Connection, OtherID);
StreamIn.play("vids");
StreamIn.client = this;
Other.videoObject.attachNetStream(StreamIn);

The Other and Self objects are of type <s:VideoDisplay>.
I'm sure it must be something pretty damn simple, but I can't seem to lay my finger on it.

A:

Never mind, I had to use mx:VideoDisplay rather than s:VideoDisplay.


Q:

Show all services on right click

Whenever you have more than 4 services, they are put in a dropdown option "Services" on right click instead of just being added to the right click menu itself.
Is this an option somewhere that can be changed?
Thanks.

A:

Services Manager seems to just modify .GlobalPreferences.plist:
defaults write -g NSServicesMinimumItemCountForContextSubmenu -int 999

You have to reopen applications to apply the changes.

A:

The little known Apple Services Manager, released via Mac OS X Automation, offers such a setting (bottom right of the main window), besides other service amenities like fine grained control over which service actually turns up in the menu.


Q:

Solenoid not embeddable in plane

I'm trying to find an reference (in English) that gives a proof that any $P$-adic solenoid (where $P$ is a sequence of prime numbers) cannot be embedded in the plane, $\mathbb{R}^2$.  So far, all the references seem to only say so, but they never give a proof.  I know Van Dantzig was the originator of the concept, but his paper is in German.  Can anyone help me find a paper or book that gives a proof and is written in English?

A:

Van Dantzig did introduce solenoids in

van Dantzig, D.. "Ueber topologisch homogene Kontinua." Fundamenta Mathematicae 15.1 (1930): 102-125.

but at the time he did not comment on the question of their planarity.
Much later Bing published a result implying that they are not planar and this appears to be the first proof of that fact.

Bing, R. H. "A simple closed curve is the only homogeneous bounded plane continuum that contains an arc." Canad. J. Math 12 (1960): 209-230.


Q:

Bash error while compiling boost with cmake

I'm trying to compile boost(as part of another library installation) but it reports to me that my gcc is broken.
when I run cmake I get
-- The C compiler identification is unknown
-- The CXX compiler identification is GNU 4.7.2
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- broken
CMake Error at /usr/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE):
  The C compiler "/usr/bin/gcc" is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: /home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp

  Run Build Command:/usr/bin/make "cmTryCompileExec3895803733/fast"

  /usr/bin/make -f CMakeFiles/cmTryCompileExec3895803733.dir/build.make
  CMakeFiles/cmTryCompileExec3895803733.dir/build

  make[1]: Entering directory
  `/home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp'

  /usr/bin/cmake -E cmake_progress_report
  /home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp/CMakeFiles
  1

  Building C object
  CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o

  /usr/bin/gcc -m64 -O3 -march=native (Default on Linux) -o
  CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o -c
  /home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp/testCCompiler.c

  /bin/sh: 1: Syntax error: "(" unexpected

  make[1]: *** [CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o]
  Error 2

  make[1]: Leaving directory
  `/home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp'

  make: *** [cmTryCompileExec3895803733/fast] Error 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:28 (project)

-- Configuring incomplete, errors occurred!

I really do not know what might be wrong. When I make my own cmake project in C I have no problems compiling it.

A:

The error you are getting is not from gcc but from /bin/sh, there is no sign that the problem is actually with gcc itself.
/usr/bin/gcc -m64 -O3 -march=native (Default on Linux) -o
CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o -c
/home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp/testCCompiler.c

/bin/sh: 1: Syntax error: "(" unexpected

Is this value (Default on Linux) something that you have entered somewhere?


Q:

SQL search configuration

I am not very good at SQL and I have a simple zipcode finder that I created for my website.  The SQL is as follows:
$query = "select * from zipcodes2 where ZipCode like \"%$trimmed%\"

*\"%$trimmed%* of course is the actual zipcode the user enters in.  It works great but now I want to make it more advance by letting the user search for city or state and not just zipcode.  I already have the columns created and they are named "City" and "State".  What exactly should I put in the SQL line?  Will I have to change any other part of the code, specifically the \"%$trimmed%\ part?

A:

This is not a great approach but you can get close to what you want with this:
$query = "select * from zipcodes2 where ZipCode like '%$trimmed%' or (CONCAT(City, ',', State) = '$trimmed')"

But you must make sure the the user's response has no white space so it comes out as Chicago,IL and not anything like Chicago, IL or Chicago , IL.
You can do this by putting this before your query:
$trimmed = preg_replace( '/\s+/', ' ', $trimmed );


Q:

Unable to delete the row, upon clicking the delete button in laravel/mysql

I have been working on an example with scratch given in:"https://laravel.com/docs/5.1/quickstart". I am unable to delete the row upon clicking the delete button!
Web/Route.php
Route::get('/', 'TaskDisplayController@taskdisplay');

Route::post('/taskdisplay', function () {
    return view('/taskdisplay');
});
Route::get('/taskdisplay', function () {
    return view('/taskdisplay');
});

Route::post('/tasklistdisplay', 'TaskDisplayController@tasklistdisplay');
Route::get('/tasklistdisplay', 'TaskDisplayController@tasklistdisplay');

Route::post('/TaskDisplay', 'TaskDisplayController@taskdisplay');
Route::get('/TaskDisplay', 'TaskDisplayController@taskdisplay');

Route::delete('/tasklistdisplay/{id}', function ($id) {
    DB::table('tasktable')->findOrFail($id)->delete();

    return redirect('/');
});

TaskDisplayController.php
class TaskDisplayController extends BaseController
{
    public function taskdisplay()
    {
        $task_ = DB::table('tasktable')->select('task','taskid','id')->get();
        return view('taskdisplay',['task'=> $task_]);
    }

    public function tasklistdisplay(Request $req)
    {
        $task_=$req->input('taskfield');
        if(DB::insert('insert into tasktable (id, task) values (1, ?)',[$task_]))
        {
            return redirect('/TaskDisplay');
        }
        else
        {
            echo "Login failed; Wrong data entered";
        }
    }
}

taskdisplay.blade.php

        Task ID
        User ID
        Task
        Options

        @foreach($task as  $tsk)
            {{$tsk->taskid }}
            {{$tsk->id }}
            {{$tsk->task }}

            <form action="/task/{{ $tsk->id }}" method="post" >
                {{ csrf_field() }}
                {{ method_field('DELETE') }}
                <button>Delete Task</button>
            </form>

            @endforeach
<input type="hidden" value={{csrf_token()}} name=_token>

Expect it to work like :https://laravel.com/docs/5.1/quickstart
But upon clicking the delete button 404 page not found is shown

A:

Adjust the action route as shown below:
action="/tasklistdisplay/{{ $tsk->id }}"

findOrFail is an eloquent function not Query Builder. So it should be:
DB::table('tasktable')->whereId($id)->delete();


Q:

C99 Enum - Need Clarification

I have reviewed this but the accepted answer doesn't make sense to me.  I should be able to define an enum in C99 as
enum WeekDays
{
    MON, TUES, WED, THURS, FRI, SAT, SUN
}days;

and utilize the enum as follows in main as
days = FRI;
if (days == FRI)
{
    printf("Thank God it's Friday!");
}

Why the additional work in the accepted answer to utilize the enum?

A:

Your code should work.  In general though the accepted answer you point to is better programming practice.  It's desirable to separate the declaration of new types from the use of those types.  For example if you wrote a library for day manipulation, you might include the enum weekdays in that library.  But that would be a bad place to define a variable for your program to use.
Over time programmers have found this sort of separation valuable.  It generally helps code be more readable


Q:

I need a word that means "easily understood or relatable to the common man"

I can't think of a word that would summarize this phrase into one coherent adjective. It's for a thesis I'm writing about a musical composer.

A:

accessible - easily understood or appreciated.

A:

Well, there's perspicuous:

Clearly expressed or presented; easy to understand

You'd definitely get points for using a difficult word to mean easily understood!  I'd recommend:

clear
clear-cut
comprehensible
explicit
intelligible
straightforward

Of which I personally prefer straightforward.


Q:

How to show only date part dynamically in gridview while using auto generated coloumn true

I want to show only the data part in grid view. I'm using auto generated column is true. So I have to write code in rowdatabound. While writing code its giving error saying;

The best overloaded method match for
  'string.ToString(System.IFormatProvider)' has some invalid arguments

if (e.Row.RowType == DataControlRowType.DataRow)
{
    e.Row.Cells[3].Text = e.Row.Cells[3].Text.ToString("MM/dd/yyyy);
}

A:

Since Text property returns string, not a DateTime, you need to parse it to DateTime first then you can get it's string representation as MM/dd/yyyy format.
I assume your e.Row.Cells[3].Text value is a standard date and time format of your CurrentCulture, you can use it as;
e.Row.Cells[3].Text = DateTime.Parse(e.Row.Cells[3].Text)
                              .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);


Q:

TypeError: 'str' object cannot be interpreted as an integer (Python)

I have a problem in the following code what happens is that insert, in an array a string and an integer, at the time of starting the code I get the following error.
TypeError: 'str' object cannot be interpreted as an integer

This error comes from the line where the IF and insert the two variables in the array noRepetidos, how can I fix this? Thank you very much to everyone who can help me.
for i in range (len(carta3)):
 for j in range (len(carta3[i])):
  counted = Counter([item for sublist in carta3 for item in sublist])
  a = counted.get(carta3[i][j])
   if(carta[i][j] in noRepetidos) == False:
    repetidos.insert(carta[i][j], int(a))

A:

Ola
It looks like you want to show the duplicate in a nested list? Try this:
counter = Counter([
    item for sublist in carta3 for item in sublist
])
repetidos = [
    (key, count) for key, count in counter.most_common()
    if count > 1
]

Chio


Q:

Increasing speed of crop, mask, & extract raster by many polygons in R?

I'm extracting the area and percent cover of different land use types from a raster  based on several thousand polygon boundaries. I've found that the extract function works much faster if I iterate through each individual polygon and crop then mask the raster down to the size of the particular polygon. Nonetheless, it's pretty slow, and I'm wondering if anyone has any suggestions for improving the efficiency and speed of my code.
The only thing I've found related to this is this response by Roger Bivand who suggested using GDAL.open() and GDAL.close() as well as getRasterTable() and getRasterData(). I looked into those, but have had trouble with gdal in the past and don't know it well enough to know how to implement it.
Reproducible Example:
library(maptools)  ## For wrld_simpl
library(raster)

## Example SpatialPolygonsDataFrame
data(wrld_simpl) #polygon of world countries
bound <- wrld_simpl[1:25,] #name it this to subset to 25 countries and because my loop is set up with that variable

## Example RasterLayer
c <- raster(nrow=2e3, ncol=2e3, crs=proj4string(wrld_simpl), xmn=-180, xmx=180, ymn=-90, ymx=90)
c[] <- 1:length(c)

#plot, so you can see it
plot(c)
plot(bound, add=TRUE)

Fastest Method so far
result <- data.frame() #empty result dataframe

system.time(
     for (i in 1:nrow(bound)) { #this is the number of polygons to iterate through
      single <- bound[i,] #selects a single polygon
      clip1 <- crop(c, extent(single)) #crops the raster to the extent of the polygon, I do this first because it speeds the mask up
      clip2 <- mask(clip1,single) #crops the raster to the polygon boundary

      ext<-extract(clip2,single) #extracts data from the raster based on the polygon bound
      tab<-lapply(ext,table) #makes a table of the extract output
      s<-sum(tab[[1]])  #sums the table for percentage calculation
      mat<- as.data.frame(tab)
      mat2<- as.data.frame(tab[[1]]/s) #calculates percent
      final<-cbind(single@data$NAME,mat,mat2$Freq) #combines into single dataframe
      result<-rbind(final,result)
      })

   user  system elapsed
  39.39    0.11   39.52

Parallel Processing
Parallel processing cut the user time by half, but negated the benefit by doubling the system time.  Raster uses this for the extract function, but unfortunately not for the crop or mask function.  Unfortunately, this leaves a slighly larger amount of total elapsed time due to "waiting around" by the "IO."
beginCluster( detectCores() -1) #use all but one core

run code on multiple cores:
  user  system elapsed
  23.31    0.68   42.01

then end the cluster
endCluster()

Slow Method:
The alternative method of doing an extract directly from the raster function takes a lot lot longer, and I'm not sure about the data management to get it into the form I want:
system.time(ext<-extract(c,bound))
   user  system elapsed
1170.64   14.41 1186.14

A:

I have finally gotten around to improving this function. I found that for my purposes, it was fastest to rasterize() the polygon first and use getValues() instead of extract(). The rasterizing isn't much faster than the original code for tabulating raster values in small polygons, but it shines when it came to large polygon areas that had large rasters to be cropped and the values extracted.  I also found getValues() was much faster than the extract() function.
I also figured out the multi-core processing using foreach().
I hope this is useful for other people who want an R solution for extracting raster values from a polygon overlay. This is similar to the "Tabulate Intersection" of ArcGIS, which did not work well for me, returning empty outputs after hours of processing, like this user.
#initiate multicore cluster and load packages
library(foreach)
library(doParallel)
library(tcltk)
library(sp)
library(raster)

cores<- 7
cl <- makeCluster(cores, output="") #output should make it spit errors
registerDoParallel(cl)

Here's the function:
multicore.tabulate.intersect<- function(cores, polygonlist, rasterlayer){
  foreach(i=1:cores, .packages= c("raster","tcltk","foreach"), .combine = rbind) %dopar% {

    mypb <- tkProgressBar(title = "R progress bar", label = "", min = 0, max = length(polygonlist[[i]]), initial = 0, width = 300)

    foreach(j = 1:length(polygonlist[[i]]), .combine = rbind) %do% {
      final<-data.frame()
      tryCatch({ #not sure if this is necessary now that I'm using foreach, but it is useful for loops.

        single <- polygonlist[[i]][j,] #pull out individual polygon to be tabulated

        dir.create (file.path("c:/rtemp",i,j,single@data$OWNER), showWarnings = FALSE) #creates unique filepath for temp directory
        rasterOptions(tmpdir=file.path("c:/rtemp",i,j, single@data$OWNER))  #sets temp directory - this is important b/c it can fill up a hard drive if you're doing a lot of polygons

        clip1 <- crop(rasterlayer, extent(single)) #crop to extent of polygon
        clip2 <- rasterize(single, clip1, mask=TRUE) #crops to polygon edge & converts to raster
        ext <- getValues(clip2) #much faster than extract
        tab<-table(ext) #tabulates the values of the raster in the polygon

        mat<- as.data.frame(tab)
        final<-cbind(single@data$OWNER,mat) #combines it with the name of the polygon
        unlink(file.path("c:/rtemp",i,j,single@data$OWNER), recursive = TRUE,force = TRUE) #delete temporary files
        setTkProgressBar(mypb, j, title = "number complete", label = j)

      }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) #trycatch error so it doesn't kill the loop

      return(final)
    }
    #close(mypb) #not sure why but closing the pb while operating causes it to return an empty final dataset... dunno why.
  }
}

So to use it, adjust the single@data$OWNER to fit with the column name of your identifying polygon (guess that could have been built into the function...) and put in:
myoutput <- multicore.tabulate.intersect(cores, polygonlist, rasterlayer)

A:

Speed up extracting raster (raster stack) from point, XY or Polygon
Great answer Luke. You must be a R wizard! Here is a very minor tweak to simplify your code (may improve performance slightly in some cases). You can avoid some operations by using cellFromPolygon (or cellFromXY for points) and then clip and getValues.
Extract polygon or points data from raster stacks ------------------------
 library(raster)
 library(sp)

  # create polygon for extraction
  xys= c(76.27797,28.39791,
        76.30543,28.39761,
        76.30548,28.40236,
        76.27668,28.40489)
  pt <- matrix(xys, ncol=2, byrow=TRUE)
  pt <- SpatialPolygons(list(Polygons(list(Polygon(pt)), ID="a")));
  proj4string(pt) <-"+proj=longlat +datum=WGS84 +ellps=WGS84"
  pt <- spTransform(pt, CRS("+proj=sinu +a=6371007.181 +b=6371007.181 +units=m"))
  ## Create a matrix with random data & use image()
  xy <- matrix(rnorm(4448*4448),4448,4448)
  plot(xy)

  # Turn the matrix into a raster
  NDVI_stack_h24v06 <- raster(xy)
  # Give it lat/lon coords for 36-37°E, 3-2°S
  extent(NDVI_stack_h24v06) <- c(6671703,7783703,2223852,3335852)
  # ... and assign a projection
  projection(NDVI_stack_h24v06) <- CRS("+proj=sinu +a=6371007.181 +b=6371007.181 +units=m")
  plot(NDVI_stack_h24v06)
  # create a stack of the same raster
  NDVI_stack_h24v06 = stack( mget( rep( "NDVI_stack_h24v06" , 500 ) ) )

  # Run functions on list of points
  registerDoParallel(16)
  ptm <- proc.time()
  # grab cell number
  cell = cellFromPolygon(NDVI_stack_h24v06, pt, weights=FALSE)
  # create a raster with only those cells
  r = rasterFromCells(NDVI_stack_h24v06, cell[[1]],values=F)
  result = foreach(i = 1:dim(NDVI_stack_h24v06)[3],.packages='raster',.combine=rbind,.inorder=T) %dopar% {
     #get value and store
     getValues(crop(NDVI_stack_h24v06[[i]],r))
  }
  proc.time() - ptm
  endCluster()

user  system elapsed
   16.682   2.610   2.530

  registerDoParallel(16)
  ptm <- proc.time()
  result = foreach(i = 1:dim(NDVI_stack_h24v06)[3],.packages='raster',.inorder=T,.combine=rbind) %dopar% {
        clip1 <- crop(NDVI_stack_h24v06[[i]], extent(pt)) #crop to extent of polygon
        clip2 <- rasterize(pt, clip1, mask=TRUE) #crops to polygon edge & converts to raster
         getValues(clip2) #much faster than extract
  }
  proc.time() - ptm
  endCluster()

user  system elapsed
   33.038   3.511   3.288


Q:

Gridview with multiple elements in each row

There is an app which has the listbox with multiple rows and there is some info in each of this rows. How to implement that? Try to use gridview in listbox?

A:

Simplest way to replicate this

Create a new Store App with Grid App Template
Replace the GridView code with this

    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <Grid Margin="1,0,0,6">
                        <Button
                            AutomationProperties.Name="Group Title"
                            Click="Header_Click"
                            Style="{StaticResource TextPrimaryButtonStyle}" >
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Title}" Margin="3,-7,10,10" Style="{StaticResource GroupHeaderTextStyle}" />
                                <TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource GroupHeaderTextStyle}"/>
                            </StackPanel>
                        </Button>
                    </Grid>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
            <GroupStyle.Panel>
                <ItemsPanelTemplate>
                    <VariableSizedWrapGrid Orientation="Horizontal" Margin="0,0,80,0"/>
                </ItemsPanelTemplate>
            </GroupStyle.Panel>
        </GroupStyle>
    </ListView.GroupStyle>
</ListView>


Q:

Where else can I declare included scripts in angular-cli?

In angular-cli.json I have:
"polyfills": "polyfills.ts"
"scripts": ["script1.ts"]

I want to add another another polyfill script for ie11 specifically, which I can then wrap in a conditional comment upon final build, in order to decrease load times on other browsers.
How would I go about including such a script so it compiled with the rest of the project at run time but was not going to be bundled into either of the above?

A:

If you want cli to output the script in a separate bundle you can use global-scripts like:
"scripts": [
    { "input": "../node_modules/module-name", "output": "module-custom-name", "lazy": true}
],

When you specify "lazy": true cli will create a separate file that will contain just your module you want to load conditionally.


Q:

Which for loop header performs better?

I see the following a lot in the Android documentation:
int n = getCount();

for (int i = 0; i < n; i ++) {
    // do somthing
}

But I'm used to seeing and doing:
for (int i = 0; i < getCount(); i ++) {
    // do somthing
}

I'm curious if one is more efficient than the other? What is exactly happening in these two scenarios? When you call getCount() in the second way, does the computer have to allocate another variable? Or is it simply a matter of code cleanliness or preference?

A:

This is what the javac compiler of JDK1.6.0_21 generates for the two cases:
First case:
int n = getCount();

for (int i = 0; i < n; i ++) {
    // do something
}

Compiled bytecode:
invokestatic example/Test/getCount()I
istore_1
iconst_0
istore_2
goto 10
... // whatever code in the loop body
iinc 2 1
iload_2
iload_1
if_icmplt 6
return

Second case:
for (int i = 0; i < getCount(); i ++) {
    // do something
}

Compiled bytecode:
iconst_0
istore_1
goto 8
... // whatever code in the loop body
iinc 1 1
iload_1
invokestatic example/Test/getCount()I
if_icmplt 4
return

It may seem that the resulting code is different, but depending on getCount(), the runtime may optimize the execution. Generally speaking, the first code seems more efficient, especially when getCount() does some complex operations to return its value.


Q:

fill half bgcolor of calendar square

I have followed this tutorial: http://www.phpjabbers.com/how-to-make-a-php-calendar-php26-6.html#comments to make a very basic calendar. My aim is to create a very basic availability calendar whereby booked days are filled in with a different color. I have managed to accomplish this however I would like to be able to indicate mornings and afternoons by filling only half of a squares background color like the following:
http://www.phpjabbers.com/availability-calendar/
Does anyone know how I could accomplish this?

A:

This is more in the domain of html/css than php. One way to accomplish what you're looking for is to simply specify css classes that style the calender days according to their respective booked statuses.
I politely decline to look at your supplied tutorial, so I'll assume you're using table <td> cells to display the calendar days. One way to accomplish your goal would be to create two images and use them as the backgrounds for cells that have the matching class:
<style>
td.booked_morning { background-image: url(lower_half.png); }
td.booked_afternoon { background-image: url(upper_half.png); }
td.booked_full { background-color: yellow; }
</style>

The same concepts apply if you were using, say, <div> elements to hold the calendar days.
You would simply use PHP to tag each calendar cell with the appropriate style.


Q:

How to send a filename through batch & accept it in Java

Ok so I might have worded this wrong, it's a little difficult to explain. So here goes:
Main Goal: Call java triangle program through batch while also piping a list of testcase.txt files with input that must be sent to the java program to determine the triangle type. WITHOUT hard typing the file name into the java program.
Problem:Not sure how to accept the fileName to use in the java application from the batch command window.
Currently, I'm just using one text file to test with containing 3 numbers separated by a space. When running the java program by itself I can type the file path to the text file & everything works as intended. But alas I can't hard code or ask the user for that path since this should be setup by the batch file to call these 15 test case files to send to the program. The part of code I have now that I dont understand is this:
        Scanner input = new Scanner(System.in);
        String fileName = input.next();
        Scanner reader = new Scanner (new File(fileName));

So I understand that input.next() is going to be asking for keyboard input how can I switch this from keyboard input to batch file input? If that makes sense.
Here is my batch file:
@ECHO off

set /P num1="Please enter file path: "

echo You entered %num1%
ECHO Checking for file...
if exist %num1% (
    set num1=Congrats! I found the file!
    C:\Users\josh\Documents\NetBeansProjects\Triangle\src\TriangleRebuild.java
) else (set num1=File does not exist)

echo %num1%

PAUSE

exit

Full Code:
/*
 * Josh

Software Engineering

Structured Triangle Implementation in Java

 */
import java.io.*;
import java.util.*;

public class TriangleRebuild {

    public static void main(String[] args) throws FileNotFoundException{
        Scanner input = new Scanner(System.in);
        String fileName = input.next();
        Scanner reader = new Scanner (new File(fileName));

        int a;

        int b;

        int c;

        boolean isATriangle;

        System.out.println("Enter 3 integers which are sides of a triangle: ");

        a = reader.nextInt();

        b = reader.nextInt();

        c = reader.nextInt();

        System.out.println("Side A is: " + a);

        System.out.println("Side B is: " + b);

        System.out.println("Side C is: " + c);

        if((a < b + c) && (b < a + c) && (c < a + b)){

            isATriangle = true;

        }

        else{

            isATriangle = false;

        }

        if(isATriangle){

            if((a == b) && (b == c)){

                System.out.println("Triangle is Equilateral.");

            }

            else if((a != b) && (a != c) && (b != c)){

                System.out.println("Triangle is Scalene.");

            }

            else{

                System.out.println("Triangle is Isosceles.");

            }

        }

        else{

            System.out.println("Not a Triangle.");

        }

        if((Math.pow(c,2) == Math.pow(a,2) + Math.pow(b,2))){

            System.out.println("Triangle is a right Triangle.");

        }

        else{

            System.out.println("Triangle is not a right Triangle.");

        }

    }

}

A:

You know that every main method is declared like this:
public static void main(String[] args) {...}

That args array represents command line arguments. That is, parameters you wrote on the java command line in your cmd window or your batch. So for example, if you have a line in your batch that says:
java TriangleRebuild abc.txt

Then inside the program, the array args will have the value { "abc.txt" }. You can access that by using args[0]. You have to make sure, of course, that args.length > 0 and that args[0] != null before you use it, just in case someone forgot to write the file name on the command line.
You can pass several file names in the command line.
java TriangleRebuild abc.txt def.txt hij.txt

And then your array will be: {"abc.txt","def.txt","hij.txt"} inside the program.
This way, you can pass argument from your batch to your Java and process them without interaction with the user.


Q:

PHP unable to load Memcached extension due to json?

It says "undefined symbol: php_json_encode" but json is installed already? also, when i add json.so to the php.ini, it say that module is already loaded?

A:

Because you add json.so into php.ini and do not remove the php.d/json.ini
Error shows the reason: json.so should be loaded before memcached.so
Please use php -m | grep memcached to check whether memcached.so is loaded successfully.

If it shows memcached, this means it has succeeded.
If its show like PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/memcached.so' - /usr/lib64/php/modules/memcached.so: undefined symbol: php_json_decode_ex in Unknown on line 0

Here is the solution:
e.g. your php.ini is /etc/php.ini, your php.d is /etc/php.d/
Solution 1

comment 'memcached.so' in php.ini
vim /etc/php.d/memcached.ini
add extension=memcached.so in /memcached.ini
php -m | grep memcached to check whether memcached is successfully loaded

Solution 2

rm /etc/php.d/json.ini
add extension=json.so in php.ini before extension=memcached.so
php -m | grep memcached to check whether memcached is successfully loaded


Q:

JavaScript shuffling deck so no three same suit

I have a homework assignment, where I create a pack of playing cards, and as a bonus I randomize them. We're supposed to randomize them so that no three cards in a row have the same suit. I have randomized them using the Fisher-Yates Method.
It works most of the time, but there is still a chance that three cards can have the same suit in a row.
How can I run a loop and scan the three cards in a row to see if they are the same suit, so that if it's true, I can run my randomize function again?
Here is my code:
var suits = ["Hearts", "Diamonds", "Spades", "Clovers"];
var faces = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "Kings", "Joker"]
var a = " of "
var deck = [];
var temp = null;

//Looping through arrays, combining faces to each suit
//Faces is length-1 to not insert all jokers
for (i = 0; i < suits.length; i++) {
  for (j = 0; j < faces.length-1; j++) {
    //Looping through each of the suits
    deck.push(faces[j] + a + suits[i])
  }
}
//Inserting 1 joker to the deck
deck.push(faces[13])
console.log(deck)

//Shuffle the deck, using Fisher-Yates shuffle
//Researched from Frank Mitchell: https://www.frankmitchell.org/2015/01/fisher-yates/

for (k = deck.length - 1; k > 0; k -= 1) {
  m = Math.floor(Math.random() * (k + 1))
  temp = deck[k]
  deck[k] = deck[m]
  deck[m] = temp
}

console.log("^^^^^^^^^^^^^^^^^^^^^")
console.log("---Shuffling Deck----")
console.log("vvvvvvvvvvvvvvvvvvvvv")
console.log(deck)

Notes: So best as what I can guess, and I know it will require more processes is to do a for loop for each suit type (running this search loop four times), then using indexOf(suits[i]), but then how do I compare that to deck[i + 1] and [i + 2]? How do I create the comparison of the suit that I'm looking for, and the suit in the deck?
Also, card elements are named in the Array: "Ace of Diamonds", "5 of Spades"

A:

You may find it easier to represent each card as an object {Suit:'Hearts', Face:'Ace'}. This will let you easily determine which suit a card is without having to do string manipulation. If you have a hard requirement to use strings to represent the cards, you could just use a regular expression to extract the word after of in your exapmle.
In terms of looking for 3 of the same suit, you don't need to look for each suit independently. Just look one card at a time and look to see if its suit matches that of i-1 and i-2 (while being mindful of the first cards of course).