text:
Q: Obstruction to this gauge choice of the connection of a vector bundle Let $M$ be a compact manifold with a nowhere-vanishing vector field $R$. Consider principal $G$-bundle $P$ over $M$, and $\mathcal{A}$ being the space of irreducible connections.
Let me denote a subspace $\mathcal{A}_R$ of all irreducible connections $\mathcal{A}$ as
\begin{equation}
    \mathcal{A}_R \equiv \{{A \in \mathcal{A}} | \mathcal{{L}}_RA = {d_A}\left( {{\iota _R}A} \right) \}
\end{equation}
where $\mathcal{L}_R$ denotes the Lie-derivative. The condition implies an infinitesimal action of diffeomorphism generated by $R$ is equivalent to infinitesimal gauge transformation with parameter $\iota_R A$, and it is equivalent to $\iota_R F_A = 0$.
My goal is to understand the space $\mathcal{A}_R$. One naive guess is that one could choose a gauge such that $\mathcal{L}_R A = 0$, since infinitesimally Lie-derivative can be compensated by gauge transformation. Note that by irreducibility it implies $\iota_R A = 0$.However this is not true in general: if some orbits $\mathcal{C}$ of $R$ is closed and $A$ has non-zero holonomy along $\mathcal{C}$, then one cannot have $\iota_R A = 0$
So my question is: Is there a way to classify the space $\mathcal{A}_R$ (modding out gauge equivalence $\mathcal{G}$), namely some decomposition (some Fourier decomposition according to behavior of $A$ under action of $R$)
\begin{equation}
    \mathcal{A}_R/\mathcal{G} = \{ A|\mathcal{L}_R A=0\}\cup \{...\}\cup\{...\}...?
\end{equation}
In particular, is there obstruction to the existence of connection $\mathcal{L}_R A = 0$?


text:
Q: Not getting how to prove reverse hypothesis. This is a theorem from Dummit & Foote text-

Let $G$ be  a group acting on the non-empty set $A$.The relation on $A$ defined by
$a \sim b$ iff $a=g.b$ for some $g \in G$
is an equivalence relation.

I've shown that  '$\sim$' is an equivalence relation.
But as this theorem is a bi-implication statement,i' don't know how to prove reverse hypothesis even i'm not getting WHAT  is it?
Need help in this.
Any suggestions are heartly welcome.
thank you!!

A: There is no equivalence (or 'bi-implication'), only the following implication:

If $G$ is a group acting on a non-empty set $A$, then the relation $\sim$ on $A$ defined by
  $$a\sim b\qquad\Leftrightarrow\qquad (\exists g\in G)(a=gb),$$
  is an equivalence relation.

The 'iff' in your question only serves to define the relation on $A$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Collinearity problem (Newton-Gauss line) I had some troubles with this problem :

Let $ABCD$ be a convex quadrilateral. $M$ and $N$ are the midpoints of
  the diagonals $AC$ and $BD$. The sides $AB$ and $CD$ are extended
  until they intersect. The intersection point is $E$. The sides $AD$
  and $BC$ are extended until they intersect. The intersection point is
  $F$. Let $P$ be the midpoint of the segment $[EF]$. Prove that $M$, $N$, $P$ are
  collinear.

First, I found that a quadrilateral in which the opposite sides interesect is also known as a complete quadrilateral.
Then, the line $M-N-P$ is known as Newton-Gauss line and the problem above as Newton's Problem.
I've taught about solving it using areas. I've used the property that median divides the triangle in two echivalent triangles (with the same area). Many properties can be derived from it.
I haven't figure out, but I'm interested in a proof using areas. I would appreciate some suggestions.
Thanks!

A: Let $S$ denote the area of $ABCD$.
Lemma 1: The locus of points $X$ in the interior of $ABCD$ such that $|XAB|+|XCD|=\frac{S}{2}$ is a line segment.
In triangle $ADE$, consider a translation of $AB$ to $ES$ and $CD$ to $ET$. Thus, $|XES|=|XAB|$ and $|XET|=|XCD|$. Thus, $|XAB|+|XCD|=|XES|+|XET|=|XSET|=|EST|+|XST|$. Since $S$ and $T$ are fixed points, it follows that $|XST|$ is constant, so the locus of $X$ is the segment made by the intersection of the line parallel to $ST$ with $ABCD$. Further note that if $X$ is outside $ABCD$, then we have $|XAB|-|XCD|=\frac{S}{2}$ or $|XCD|-|XAB|=\frac{S}{2}$.$_\square$
Note that since $M$ is the midpoint of $AC$, $|AMB|=|BMC|$ and $|AMD|=|CMD|$, so $|AMB|+|CMD|=\frac{S}{2}$, so $M$ lies on the locus of $X$. Similarly, $N$ lies on the locus of $X$.
Now note that since $EP=PF$, $|PAB|=\frac{1}{2}|FAB|$ since the distance between $P$ and $AB$ is half of the distance between $F$ and $AB$. Similarly, $|PCD|=\frac{1}{2}|FCD|$. Thus, we have $|PAB|-|PCD|=\frac{1}{2} (|FAB|-|FCD|) = \frac{S}{2}$, so $P$ also lies on this line.
Therefore, $M$, $N$, $P$ are collinear.

A: In fact there is an alternate, nice, proof using areas that I got, using a link found in the Wikipedia article, in the book by Johnson,  "Modern geometry; An Elementary Treatise on the Geometry of the Triangle and the Circle, Houghton Mifflin Ed., 1929" available online (public domain), page 61-62.
I reproduce here the two pages.

Nice, isn't it ?


text:
Q: How can i get constituents of a member function from its address? Is it possible to get the constituents of a member function such as class type or return type just from its address (not from member function type) ?
For e.g. given
 class foo
 {
    int bar()
    {
        return 5;
    }
 };

i like to have
is_same< function_types<&foo::bar>::class_type, foo>::value == true;

I also know additionally that the member function has a signature like R (C::*)() i.e no arguments and no cv-qualification.
Thank you.

A: You can capture the type in a template function:
#include <iostream>

struct foo {
    foo() { std::cout << "OK\n"; }
    int bar() {return 0;}
};

template<typename C, typename R>
bool thing(R (C::*)()) {
    C x;
}

int main() {
    thing(&foo::bar);
}

prints "OK", so you could put your is_same check in there. I'm really not sure what the question is, though - obviously here we are using the type of the member function for template argument deduction.
If you've somehow invalidly reinterpret_cast a member function pointer to something else, so as to discard its type, then no you can't recover it.
If you've converted your member function pointer to a compatible member function pointer type, for example R (B::*)() -> R (D::*)(), where B is a base class of D, then I think you can use dynamic_cast to test whether it really is a B function after all. You can't recover the type that way, just the typeid of the member function pointer, because it's a runtime operation. Types really only exist at compile-time in C++, so there's no way to "get" the dynamic type of a value, whether that value is a member function pointer or anything else. The compiler either knows it, or it doesn't, and if it does then there's various template trickery to actually use the constituents of that type.

A: Nope. This is part of what is called run-time reflection and is not possible in such low-level language as C++. You cannot get this data from only the address.
Whatever you're doing, in C++ you're likely to be able to do this with a metaprogramming approach, using template magic or preprocessor magic. For example, Boost libraries rely on such approach.

A: In C++ pre-0x, you can't do this very easily. In C++0x, you can use a combination of template functions and decltype to do this:
template <typename R> struct unary_function_info { typedef R result_type; typedef void class_type; };
template <typename R> unary_function_info get_function_info(R (*)());

template <typename C, typename R> struct unary_member_function_info { typedef R result_type; typedef C class_type; };
template <typename C, typename R> unary_member_function_info get_function_info(R (C::*)());

is_same<decltype(get_function_info(&foo::bar))::class_type, foo>::value == true;

And then expand the above out for as high an arity as you need.

A: You could use overloading:
void F(int);
void F(bool);

F(foo.bar());

You can use template functions and partial specialisation for a more generic solution.

A: struct char2_t { char xxx[2]; };

template <bool flag, typename T, typename U> struct select   { typedef T type; };
template <typename T, typename U> struct select<false, T, U> { typedef U type; };

template<class Foo, class C, class R>
typename select<boost::is_same<Foo, C>::value, char, char2_t>::type test(R (C::*)());

void check_in_this_function() {
 char check_arr1[ sizeof(test<foo>(&foo::bar))==1 ? 1 : -1];
 char check_arr2[ sizeof(test<int>(&foo::bar))==1 ? 1 : -1];  // error: negative subscript
}

A: If for some reason you are passing around a member function pointer as a simple type, you can get the constituent parts with something like the following. (This requires C++0x, in current C++ making it support arbitrary arities would take a lot more work.)
#include <tuple>

template <class T>
struct method_traits;

template <class ReturnType, class ObjectType, class... ArgTypes>
struct method_traits<ReturnType (ObjectType::*)(ArgTypes...)>
{
    typedef ReturnType result_type;
    typedef ObjectType object_type;
    template <unsigned N>
    struct argument
    {
        typedef typename std::tuple_element<N - 1, std::tuple<ArgTypes...>>::type type;
    };
};

template <class ReturnType, class ObjectType, class... ArgTypes>
struct method_traits<ReturnType (ObjectType::*)(ArgTypes...) const>
{
    typedef ReturnType result_type;
    typedef ObjectType object_type;
    template <unsigned N>
    struct argument
    {
        typedef typename std::tuple_element<N - 1, std::tuple<ArgTypes...>>::type type;
    };
};

struct Foo
{
    int bar(double, float) const ;
};

template <class MemberFun>
void test(MemberFun f)
{
    typename method_traits<MemberFun>::result_type result;
    typename method_traits<MemberFun>::object_type object;
    typename method_traits<MemberFun>::template argument<1>::type i = 10;  //:)
    result = (object.*f)(i, 2.0f);
}

int main()
{
    test(&Foo::bar);
}


text:
Q: Sub-document in an array saves as an empty array item if no value is provided on document creation What I want is for a particular field in my schema to be an array with items in it.
When I create the document in question, I will not have any array items. Therefore, I expect my document to look like:
{
  notes: []
}

The problem is, I'm getting an array that looks like:
{
  notes: ['']
}

Querying the notes.length, I get 1, which is problematic for me, because it's essentially an empty array item.
This is the code I'm working with:
const SubDocumentSchema = function () {
  return new mongoose.Schema({
    content: {
      type: String,
      trim: true
    },
    date: {
      type: Date,
      default: Date.now
    }
  })
}

const DocumentSchema = new mongoose.Schema({
    notes: {
      type: [SubDocumentSchema()]
    }
});

const Document = mongooseConnection.model('DocumentSchema', DocumentSchema)
const t = new Document()

t.save()

A: You can specify empty array as the default value for notes. And you don't need to return a function for the SubDocumentSchema. Try the below edited code.
const SubDocumentSchema = new mongoose.Schema({
  content: {
    type: String,
    trim: true
  },
  date: {
    type: Date,
    default: Date.now
  }
})

const DocumentSchema = new mongoose.Schema({
  notes: {
    type: [SubDocumentSchema],
    default: []
  }
});

const Document = mongooseConnection.model('DocumentSchema', DocumentSchema)
const t = new Document()

t.save()


text:
Q: Simple AngularJS Routing example does not work I am following this simple example of AngularJS about Routing: https://www.w3schools.com/angular/tryit.asp?filename=try_ng_routing
I created two pages:
index.htm
<!DOCTYPE html>

Main

Red
Green
Blue

Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back to "main.htm"

red.htm
<!DOCTYPE html>

      <title>Red</title>

Red

The routing to red page does not work.


text:
Q: JS: Most efficient way to filter results by iterating? I have a variable called data and have it defined to a list like this:
[
  {
    name: "Richard",
    searchable_names:["rich", "dick", "richard", "richie"]
  },
  {
    name: "Anthony",
    searchable_names:["tony", "anthony"]
  },
]

Using onKeyUp in the search bar, I am trying to filter the results into a new array and display those like this but I realize this is an O(N^2) nested loop and not the most efficient way of doing it.  What is a better way for me to resolve this inefficiency:
data.forEach(name => {
    name.searchable_names.forEach(x => {
        if (x.toLowerCase().includes(searchBar.text.toLowerCase())) {
            arr.push(name);
        }
    })
})

A: Having nested for loops doesn't always mean the time complexity is O(n^2).
In your code, you are visiting each array item and its searchable_names array only once, so the time complexity is O(n * m).
To improve efficiency:
1) You could use a regular for loop instead of inner forEach() and break when you find a searchable name. This way you wouldn't have to continue searching the inner searchable_names array when you already find a match.
Using regular for loop because there's no built-in ability to break in forEach().
2) Or instead of nested for loops, you could use filter(), some(), and map() methods. This approach gives almost the same time complexity of using break; with for loops.
let arr = data.filter(item =>
  item.searchable_names.some(
    x => x.toLowerCase().includes(searchBar.text.toLowerCase())
  )
).map(item => item.name);

A: For smaller list let say up to 100.000 strings that should work just fine. To keep things simple things you can do is to move toLowerCase out of loop and use filter and find functions.
var data = [
  {
    name: "Richard",
    searchable_names:["rich", "dick", "richard", "richie"]
  },
  {
    name: "Anthony",
    searchable_names:["tony", "anthony"]
  },
]

function filterData(data, value) {
    const valueLowerCase = value.toLowerCase();
    return data.filter(item => {
      return item.searchable_names.find(
        x => x.toLowerCase().includes(valueLowerCase)
      )
    })
}

const result = filterData(data, "a");
console.log(result);

A: You can use array.Filter()

const data = [
  {
    name: "Richard",
    searchable_names:["rich", "dick", "richard", "richie"]
  },
  {
    name: "Anthony",
    searchable_names:["tony", "anthony"]
  },
]

function searchName(key) {
  return data.filter(x =>
    x.searchable_names.some(n => n.includes(key.toLowerCase()))
  )
}

console.log(searchName("ri"));


text:
Q: Sacar coordenadas de diferentes div con drag y drop JavaScript Estoy realizando un proyecto en el cual manejo drag y drop de JavaScript. Ahora ya tengo los divisores que se arrastran pero me piden que saque las coordenadas x,y de cada uno y ahí es donde está el problema: no sé cómo hacerlo pues al arrastrar cualquier div las coordenadas x,y toman el valor del último que se arrastró.
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Drag and Drop</title>

  HC

  PO

        <form id="form-ingreso">
            <input type="text" id="x"  />
            <input type="text" id="y"  />
            <input type="text" id="x1"  />
            <input type="text" id="y1"  />
        </form>

A: Cuando termina el drag, se gatilla una función que recibe como parámetro el evento. Ese evento contiene el elemento que acabas de arrastrar. Está en event.target.
Una manera no muy elegante (pero rápida) de hacer lo que pides es hacer que los ID de cada input calcen con el ID del elemento más un sufijo (x e y). De esa manera, al soltar un elemento, leyendo su ID puedes saber qué inputs actualizar:

interact('.draggable').draggable({
  // enable inertial throwing
  inertia: true,
  // keep the element within the area of it's parent
  restrict: {
    restriction: "parent",
    endOnly: true,
    elementRect: {
      top: 0,
      left: 0,
      bottom: 1,
      right: 1
    }
  },
  // enable autoScroll
  autoScroll: true,

  // call this function on every dragmove event
  onmove: dragMoveListener,
  // call this function on every dragend event
  onend: function(event) {
    var element = event.target;
    document.getElementById(element.id + 'x').value = element.getAttribute('data-x');
    document.getElementById(element.id + 'y').value = element.getAttribute('data-y');

  }

});

function dragMoveListener(event) {
  var target = event.target,
    // keep the dragged position in the data-x/data-y attributes
    x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
    y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

  // translate the element
  target.style.webkitTransform =
    target.style.transform =
    'translate(' + x + 'px, ' + y + 'px)';

  // update the posiion attributes
  target.setAttribute('data-x', x);
  target.setAttribute('data-y', y);

}

// this is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener;
#drag-1,
#drag-2 {
  width: 3px;
  height: 5px;
  background-color: #29e;
  color: white;
  border-radius: 0.75em;
  padding: 3%;
  -webkit-transform: translate(0px, 0px);
  transform: translate(0px, 0px);
}

#drag-me::before {
  content: "#" attr(id);
  font-weight: bold;
}

 HC

 PO

<form id="form-ingreso">
   Elemento 1
    <input type="text" id="drag-1x"  />
    <input type="text" id="drag-1y"  />

   Elemento 2
    <input type="text" id="drag-2x"  />
    <input type="text" id="drag-2y"  />

</form>


text:
Q: How to make an RxJS subscription with an async function serialize the onNext calls? This is a followup for this question.
So RxJS is calling my async function with the next event bebore the previous one has completed as soon as I await in my async method.
I need to serialize the calls to this async function.
I have understood from this answer to a similar question that I need to move my async function away from subscribe and use concatMap.
Right now my code does not compile with the following error:

error TS2339: Property 'concatMap' does not exist on type 'Observable'.

My code (trying to adjust):
1/ the new subscription code (won't compile):
this.emitter = fromEventPattern(this.addHandler, this.removeHandler, (err, char) => [err, char]); <= unchanged
this.rxSubscription = this.rxSubscription = this.emitter.concatMap(value:any => this.handleUpdatedValuesComingFromSensor(value)).subscribe(); <= concatMap does not exist on type Observable<any>

2/ the async function for your information:
       handleUpdatedValuesComingFromSensor = async (arr: any[]): Promise<void> => {
   ...
   await someMethodAsync();
   ...
}

concatMap should be used on another type of source but I can't figure it out.
Thanks in advance.

A: As Kos stated, in Rxjs v6, pipeable operators became the norm, moving away from chaining everything together with ..
I assume since you're using fromEventPattern, instead of Observable.fromEventPattern that you are using rxjs v6+, in which case, you need to wrap concatMap() inside a pipe().
this.rxSubscription = this.emitter.pipe(concatMap(value:any => this.handleUpdatedValuesComingFromSensor(value))).subscribe()


text:
Q: Group of matrices which share a fixed eigenvector is noncommutative Let $n\in\mathbb{N}$, $n>1$, $v\in\mathbb{R}^n$. Let $X=\{A\in GL_n(\mathbb{R})\mid Av=\lambda v\text{ for some }\lambda\in \mathbb{R}\}$. Then $X$ is a noncommutative group.
It is easy to show, that $X$ is a group. But how do I show non commutativity? I can definitely construct counterexamples, but I think there should be a general argument that works for an arbitrary $v$.

A: With respect to any basis $(v,b_1,\ldots,b_{n-1})$ these are precisely the matrices of the form
$$\begin{pmatrix}\lambda&u\\0&B\end{pmatrix},$$
with $u\in\Bbb{R}^{n-1}$ and $B\in\operatorname{GL}_{n-1}(\Bbb{R})$, which clearly do not all commute.

A: Since you said that you can construct counter-examples, let $A$ and $B$ be two matrices which do not commute but which have $w$ as an eigenvector. Now, let $C$ be an invertible matrix such that $Cw=v$ (we can construct such a matrix by completing $\{v,w\}$ to a basis and then writing the matrix which interchanges $v$ and $w$ but leaves all other basis vectors fixed). Consider $A'=CAC^{-1}$ and $B'=CBC^{-1}$. It is easy to check that $v$ is now and eigenvector of $A'$ and $B'$. Furthermore, if $A'B'=B'A'$ then we see that $CABC^{-1}=CBAC^{-1}$ which implies that $AB=BA$, a contradiction. Basically, we have just taken advantage of the fact that given a matrix having some eigenvector, we can change basis in a way such that another vector is an eigenvalue.

A: Matrices with distinct eigenvalues don't commute with non-diagonalisable matrices. I believe it is clear that the group contains both kinds of matrices.


text:
Q: Configure ceph block storage pool in cockpit I have a plain install on machine C with Oracle Linux 9.1 and cockpit and cockpit-machines. On machines A and B I have a ceph cluster configured which defines an rbd block storage pool for VM disks. Having copied a minimal config and the keyrings onto machine C I can "access" the ceph cluster as in the command ceph osd lspools on machine C returns all configured pools as expected.
In the cockpit UI however, the only options I see for configuring a new storage pool, are filesystem and network file system, nothing else.
How can I configure the existing rbd storage pool to be available to new VMs I create in the cockpit UI?

A: I'm not familiar with cockpit but with ceph. Reading the cockpit docs I would probably choose physical disk as source, and the physical disk is a mapped rbd device. If you already have a pool dedicated for rbd usage, I would create one (or more) rbd images in required size:
rbd -p <pool> create -s <size> <name>

Then map that rbd device on the hypervisor, for automatic mapping after boot there's an example file within the /etc/ceph directory:
# cat /etc/ceph/rbdmap
# RbdDevice             Parameters
#poolname/imagename     id=client,keyring=/etc/ceph/ceph.client.keyring

To enable the map after boot you need to enable the rbdmap service:
# systemctl enable --now rbdmap.service
● rbdmap.service - Map RBD devices
   Loaded: loaded (/usr/lib/systemd/system/rbdmap.service; disabled; vendor preset: disabled)
   Active: inactive (dead)

When the rbd image is mapped to the hypervisor you should see it in lsblk output as an rbd device, or in /dev/rbd as well:
# lsblk
NAME                MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sr0                  11:0    1  458K  0 rom
rbd0                252:0    0   10M  0 disk

# ls -l /dev/rbd0
brw-rw---- 1 root disk 252, 0  9. Feb 12:18 /dev/rbd0

So from the hypervisor's perspective it's now a local disk which you can use to create storage pools.

A: While creating rbd storage pools in the Cockpit UI is currently impossible, I found a way of creating the pool for use with libvirt. The pool is properly displayed in the UI and I can also create new volumes there.

*

*Log in to your ceph admin node and create a new client token:

ceph auth get-or-create client.libvirt mon 'allow r' osd 'allow class-read object_prefix rbd_children, allow rwx pool=mypool'

*Log in to your virtualization host (the machine managed with Cockpit) and configure the pool for libvirt.

virsh secret-define --file secret.xml
virsh secret-set-value --secret UUID --base64 "$(ceph auth get-key client.libvirt)"
virsh pool-define mypool.xml

*The pool should now be visible in the Cockpit UI, can be activated and new volumes can be created.

The configuration files should look similar to those:
<secret ephemeral='no' private='no'>
  <uuid>UID</uuid>
  <usage type='ceph'>
    <name>client.libvirt secret</name>
  </usage>
</secret>

<pool type="rbd">
  <name>mypool</name>
  <source>
    <name>mypool</name>
    <host name='CEPH_MON_IP'/>
    <auth username='libvirt' type='ceph'>
      <secret uuid='UUID'/>
    </auth>
  </source>
</pool>


text:
Q: How can I change the order of keys in a NSDictionary I have a mutable array that consist of array of dictionaries as:
(
      {
        A = Mango;
        B = "John";
        C = SLOVAKIA;
        D = 01/27/13;
        E = 2000;
    },
        {
        A = Banana;
        B = "Johny";
        C = THAILAND;
        D = 02/27/13;
        E = 4000;
    },
        {
        A = Orange;
        B = "Lezin";
        C = US;
        D = 03/27/13;
        E = 6000;
    }
)

Now I want to sort the array based on the keys so that the order of the keys become BECAD which is neither ascending nor descending order,it is a random order.
Expected output is as follows:
(
      {
        B = "John";
        E = 2000;
        C = SLOVAKIA;
        A = Mango;
        D = 01/27/13;
    },
        {
        B = "Johny";
        E = 4000;
        C = THAILAND;
        A = Banana;
        D = 02/27/13;
    },
        {
        B = "Lezin";
        E = 6000;
        C = US;
        A = Orange;
        D = 03/27/13;
    }
)

How can I do that?

A: There is no inherent order to dictionary keys guaranteed. In practice, they appear to be FILO order. But it's an implementation detail.
You should use a proxy like NSArrayController to get sorting you want.

A: NSMutableDictionary always returns keys in a disordered manner.
If we really want to maintain order then we may need to  add 01, 02 ,03 Serial Numbers before/after the Keys to sort them in the order we want to put it and then we need to trim the numeric part of the String and use it.


text:
Q: GRUB and boot-repair An error occurred during the repair. Data missing I have a laptop with four drives. One drive (encrypted) for Ubuntu, one for windows, and 2 for storage. I recently installed windows after having my Ubuntu setup and working. After the windows 10 install I was unable to boot ubuntu normally. On boot I would see the grub minimal BASH like line editing. Being unfamiliar with it I turned to boot-repair. I had to use a live ubuntu install disc to get boot-repair to even work. I was getting warnings about my encrypted drive not mounting and boot-repair being unable to verify the content. I proceed anyway. Here is the output
https://paste.ubuntu.com/p/Crx9SYpYP4/
There are many unsolved post on this issue. My main concern at this point is recovering the data on the drive. If it's not possible I'll have to do a fresh install, but that will mean I lose data that I can't recover. Please help!
Another strange thing is that when I check my BIOS I see Ubuntu showing up on 3 different drives now. I can't explain it or fix it.

A: The best (of fastest was) way is to do a fresh install of Ubuntu (always install Windows before installing Ubuntu).
Of course you want not lose any data.  So you have to boot Ubuntu first from the installation medium, en select 'Try Ubuntu without installing'. Then  go to the terminal  and mount the file-system  "mount - o rw,remount / ". So you can enter in Ubuntu and do what you have to do. (backup).  If necessary do something research of booting the file system with the installation medium.


text:
Q: How to update resource detail view without reloading the whole page in laravel nova? I'd like to update an element value without reloading the whole page on the resource detail view page. I made a custom card for the device status enable/disable button. And I displayed the resource detail below my custom card. If I switch the device status button, the device status is changed to 0 or 1 in database. I did it with axios without reloading the page. But the problem is I can't update the Status field on the resource detail view without reloading the whole page. If I reload the page, then the status field shows the changed status correctly. Please look at this for understanding - https://prnt.sc/sd3jut
How can I update Status field without reloading the whole page? If possible, I'd like to do this in axios return section.
Thanks.


text:
Q: Error en plantilla: invalid use of incomplete type Encontré esto en Internet:
#include <utility>
#include <type_traits>

namespace details {

template< typename F, typename Tuple, bool Done, int Total, int... N > struct call_impl {
  static void call( F f, Tuple && t ) {
    call_impl< F, Tuple, Total == 1 + sizeof...( N ), Total, N..., sizeof...( N ) >::call( f, std::forward< Tuple >( t ) );
  }
};

template< typename F, typename Tuple, int Total, int... N > struct call_impl< F, Tuple, true, Total, N... > {
  static void call( F f, Tuple && t ) {
    f( std::get< N >( std::forward< Tuple >( t ) )... );
  }
};

} // namespace details.

template< typename F, typename Tuple > void call( F f, Tuple &&t ) {
  //typedef typename std::decay< Tuple >::type ttype;
  using ttype = typename std::decay< Tuple >::type;

  details::call_impl< F, Tuple, 0 == std::tuple_size< ttype >::value, std::tuple_size< ttype >::value >::call( f, std::forward< Tuple >( t ) );
}

Sirve para desempaquetar una std::tuple sobre los argumentos de una llamada a función.
La idea es posponer una llamada a función hasta que sea necesario, almacenando los argumentos pasados en una std::tuple y pudiendo recuperarlos en un momento posterior.
Desafortunadamente, la template solo trabaja con funciones void. La estoy intentando adaptar para poder usarla en funciones con cualquier tipo de retorno, pero no lo estoy consiguiendo:

error: no matching function for call to 'call(int (&)(int), std::tuple<int>&)'
  ...
  error: invalid use of incomplete type 'class std::result_of<int (*)(int)>'

#include <tuple>
#include <functional>
#include <type_traits>

#include <iostream>

namespace details {

template< typename RET, typename F, typename Tuple, bool Done, int Total, int... N > struct call_impl {
  static RET call( F f, Tuple && t ) {
    return call_impl< RET, F, Tuple, Total == 1 + sizeof...( N ), Total, N..., sizeof...( N ) >::call( f, std::forward< Tuple >( t ) );
  }
};

template< typename RET, typename F, typename Tuple, int Total, int... N > struct call_impl< RET, F, Tuple, true, Total, N... > {
  static RET call( F f, Tuple && t ) {
    return f( std::get< N >( std::forward< Tuple >( t ) )... );
  }
};

} // namespace details.

template< typename F, typename Tuple, typename RET = typename std::result_of< F >::type > RET call( F f, Tuple &&t ) {
  //typedef typename std::decay< Tuple >::type ttype;
  using ttype = typename std::decay< Tuple >::type;

  return details::call_impl< RET, F, Tuple, 0 == std::tuple_size< ttype >::value, std::tuple_size< ttype >::value >::call( f, std::forward< Tuple >( t ) );
}

int dummy( int );

int main( ) {
  auto tp = std::make_tuple( 10 );
  auto ret = call( dummy, tp );

  std::cout << "Retorno: " << ret << std::endl;

  return 0;
}

int dummy( int v ) {
  std::cout << "dummy( " << v << " )\n";
  return v + 1;
}

Nota: compilado con g++ -Wall -Wextra -std=c++11 -pedantic

A: El problema que tienes es que F como tal no contiene la firma de la función sino el tipo asociado a la misma... para deducir el valor de retorno es necesario pasarle los parámetros (piensa, por ejemplo, en el caso de funciones sobrecargadas).
Peeero claro, no le puedes pasar los parámetros porque están contenidos dentro de la tupla:
template< typename F, typename Tuple, typename RET = typename std::result_of< F >::type > RET call( F f, Tuple &&t ) {
//                             ^^^^^

Así pues necesitamos extraer esos parámetros para ser capaces de deducir el tipo de retorno.
Seguramente se pueda dejar más bonito, pero ahora mismo no tengo tiempo de limpiar el código mucho más.
El código no va a compilar, tal y como está planteado, con la sintaxis move, por eso he quitado esa característica... pero estoy trabajando en ello:
template< typename F, typename ... Args, typename ReturnType = typename std::result_of<F&(Args...)>::type>
ReturnType call( F const& f, std::tuple<Args...> t ) {
  using ttype = typename std::decay<std::tuple<Args...>>::type;

  return details::call_impl<ReturnType, F, std::tuple<Args...> , 0 == std::tuple_size< ttype >::value, std::tuple_size< ttype >::value >::call( f, std::forward< std::tuple<Args...> >( t ) );
}


text:
Q: Gestures with Delphi (prior to D2010) Has anyone heard of third party mouse gesture support for versions of Delphi prior to Delphi 2010? All I want is to be able to respond to a right mouse hold down for "swipe left" and "swipe right".

A: A swipe left or swipe right is nothing else than a comparison between your X-Coordinates.
Just compare your X-Coordinate in your OnMouseDown Event with the X-Coordinate in your OnMouseUp Event.
If the result is positive, it's a Swipe-Left. If the result is negative, it's a Swipe-Right.


text:
Q: Using a string as a variable at run time I have a string, which has been created at runtime. I want to use this string as a variable to store some data into it. How can I convert the string into a variable name?

A: Now simply using instance_variable_set method, you can create a instance variable at runtime.
instance_variable_set('@' + 'users', User.all)

A: If you can forgive an @ sign in front of the variable name, the following will work:
variable_name = ... # determine user-given variable name
instance_variable_set("@#{variable_name}", :something)

This will create a variable named @whatever, with its value set to :something. The :something, clearly, could be anything you want. This appears to work in global scope, by declaring a spontaneous Object instance which binds everything (I cannot find a reference for this).
The instance_variable_get method will let you retrieve a value by name in the same manner.
instance_variable_get("@#{variable_name}")

A: I don't mean to be negative, but tread carefully. Ruby gives you a lot of features for highly dynamic programming such as define_method, storing blocks as Proc objects to be called later, etc. Generally these are cleaner code and far safer. 99% of the time using eval() is a mistake.
And absolutely never use eval() on a string that contains user submitted input.

A: You can use eval() for this provided that you've declared your variable first:
>> foo = []
>> eval("foo")[1] = "bar"
>> foo[1]
=> "bar"

Here are the docs.

A: Rather than do that directly, why not consider using a hash instead. The string would be the key, and the value you want to store would be the value. Something like this:
string_values = { }
some_string = params[:some_string]       # parameter was, say "Hello"
string_values[some_string] = 42
string_values                            # { 'Hello' => 42 }
some_number = string_values[some_string]
some_number                              # 42

This has a couple of benefits. First, it means you're not doing anything magic that might be hard to figure out later. Second, you're using a very common Ruby idiom that's used for similar functionality throughout Rails.

A: As Jason Watkins says, a lot of people might be quick to use eval() first thing and this would be a serious mistake. Most of the time you can use the technique described by Tack if you've taken care to use a class instance variable instead of a local one.
Local variables are generally not retrievable. Anything with the @ or @@ prefix is easily retrieved.


text:
Q: Math in subsection title and incorrect PDF sections' sidebar I have a subsection named \subsection{$Rp_{\widehat{Y},*}(\mathcal{P})$ has property bla and bla}. I would like to keep this as title of my subsection, but it creates problems.
My code is the following.
\documentclass[a4paper,12pt,oneside]{article}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{amsmath,amscd}
\usepackage[english,italian]{babel}
\usepackage{latexsym}
\usepackage{graphicx,subfigure}
\usepackage[a4paper,top=30mm,bottom=30mm,left=30mm,right=30mm]{geometry}
\usepackage{tikz}
\usetikzlibrary{matrix,arrows,decorations.pathmorphing}
\usepackage{hyperref}
\usepackage{accents}
\usepackage[babel]{csquotes}
\usepackage[maxnames=99,style=alphabetic,backend=bibtex]{biblatex}

\begin{document}

\subsection{$Rp_{\widehat{Y},*}(\mathcal{P})$ has property bla and bla}

\end{document}

If I keep it like this, it compiles giving multiple warnings about "Token not allowed in a PDF string". In this case the main problem is that the sidebar index of sections of the outcome PDF carries "RpY"0362Y,*P bla and bla" instead of the correct title with the math.
Furthermore, if I replace \widehat by \hat, it gives the error "Tex capacity exceeded", and it does not compile.
If I replace \subsection{$Rp_{\widehat{Y},*}(\mathcal{P})$ has property bla and bla} (or the version with \hat) with \subsection[just text]{$Rp_{\widehat{Y},*}(\mathcal{P})$ has property bla and bla} then I get no error. On the other hand, I still don't get what I want in the sidebar, since I would really like the math to be there as well.
How can I have the PDF compiling correctly and carrying the right math on the sidebar as well?


text:
Q: Split on pattern in zsh I want to do something like ${(@s/<->/)param} where <-> is a pattern for numbers. If param=a567b38c898d then I'd get (a b c d).
Note: This is not the only case I'd like to solve, so a general solution would be preferred.

A: I'm not sure you can split on patterns, only on literal text. (Although this being zsh, I may be wrong and just need to do a little more research.) However, I have found how to use the substitution modifier to replace strings of characters with a specific string which you can subsequently split on. (You'll need to set the hist_substpattern option to allow a pattern as the left-hand side of the substitution operator. Still looking if there is a way to enable that just for a single modifier.)
$ param=a567b38c898d
$ setopt hist_substpattern
$ print -l ${(s/1/)param:gs/<->/1}
a
b
c
d

First, the modifier :gs/<->/1 replaces each string that matches the pattern <-> (i.e., the numbers) with a single 1. Then, the expansion flag (s/1/) splits the string on the .


text:
Q: A closed form relation to compute the spectral norm of a 2x2 real matrix I am reading this book (page 215) and I found in the bottom of this page an interesting relation that I want to use. The relation is
$$||A||_2 = \sqrt{\frac{||A||_F^2 + \sqrt{||A||_F^4 - 4 (\mathrm{det}\:A)^2}}{2}},$$ where
$$A = \begin{bmatrix}a & b \\ c & d\end{bmatrix}$$ is a $2x2$ real matrix. The relation can be verified by using the definition of the spectral norm of $A$, i.e.,
$$||A||_2 = \sqrt{\lambda_\max (A^TA)}, $$ where $\lambda_\max (A^TA)$ is the maximum eigenvalue of $A^TA$. Solving
$$\mathrm{det}\: ( A^TA - \lambda \:I )=0$$ w.r.t. $\lambda$ we get the polynomial
$$p(\lambda) = \lambda^2 - ||A||_F^2\:\lambda + (\mathrm{det}\:A)^2=0$$ with discriminant
$$\Delta = ||A||_F^4 - 4(\mathrm{det} \:A)^2.$$ Thus, the maximum root of $p(\lambda)$ is
$$\lambda_\max(A^TA) = \frac{||A||_F^2 + \sqrt{||A||_F^4 - 4 (\mathrm{det}\:A)^2}}{2}$$ which is what the author in the book uses to get $||A||_2$, My question is, how do we know that $\Delta > 0$? Is there an inequality that gives an appropriate relation between $||A||_F$ and $\mathrm{det}\:A$ ? Could you please someone cast some light?
The author also has an exercise 2.8.8 where the square is missing in the determinant. Maybe it is a mistake.

A: For any $n \times n$ positive semidefinite matrix M we have
$$
\frac{\operatorname{tr}(M)}{n} \geq \operatorname{det}(M)^{1 / n}
$$
And $A^T A$ is a special case of positive semidefinite matrix for any matrix $A$.
Since $\left(\operatorname{tr} A^{T} A\right)^{1 / 2} = \|A\|_{F}$ we have using the inequality above,
$$\|A\|_{F}^{4} = \left(\operatorname{tr} A^{T} A\right)^2 \geq n^2 (\det({A^TA}))^\frac{2}{n} = n^2 \det({A})^\frac{4}{n} $$
The special case for n=2 is given by :
$$\|A\|_{F}^{4} \geq 4 \det(A)^2$$
which is exactly what you want.
Of course there is possibly a much easier way to derive this inequality in the case of a $2 \times 2$ matrix !


text:
Q: Is there a way to make an Azure DevOps release only publish the actual latest change from a build pipeline? I have a situation where two commits were merged to master (e.g. FIRST and SECOND) very close together (seconds apart). Both triggered the build pipeline: FIRST triggered the pipeline first and SECOND triggered it second (the builds ran in parallel). For whatever reason, the build pipeline for commit SECOND finished first, and 30 seconds later the build for commit FIRST finished.
My automatic release pipeline is configured to always get the "latest" artifact from the build pipeline. The sequence of events described above caused the SECOND change to be deployed first, and then the FIRST change was deployed next (since its pipeline finished second) and stomped on the prior release, effectively deploying old bits to the service.
Is there any way to prevent this situation? Even if a build pipeline finishes second for intermittent reasons, I don't want a release to stomp over a more recent change that happened to finish earlier.
EDIT: Thank you to those who suggested/supported the idea of batching builds but that's not an option I'm looking to enable. I still want each commit to trigger its own build (to enable easier assignment of build break cause). I'm just looking for the releases to trigger in the order of commits, not the order of builds finishing.
Thanks!

A: You can set batch to true in triggers, so the system waits until the build is completed. Set "Batch changes while a build is in progress" option to true in Triggers for Build Pipeline at Azure DevOps or in YAML:
trigger:
  batch: true

If you use Pull request, there should be no issues as new push should cancel in-progress run. Check autoCancel in PR triggers

A: You may need to make the pipelines to run on the same agent. So that the newest queue will wait for the previous queue to complete.
You can follow below steps to confine your pipeline to one agent.
1, Add a custom capability to the agent you want to run the pipeline(project settings->agent pools(select an agent pool)->agents(select a agent)->capabilities)

2,Add a demand to your pipeline : # this works for both microsoft-hosted agents and self-hosted agents

I tested and found microsoft-hosted agent pool doesnot support demands for custom capabilities in yaml pipeline.
Below yaml pipeline works only for self-hosted agent pool.
pool:
  name: Default
  demands: Tag -equals Agent1


text:
Q: C# create firewall rule to allow system to respond to pings? I inherited a  C# application and working on it. It creates some firewall rules programmatically.  By default it disables everything on a specific interface, then allows a few specified TCP ports access, which is fine.  I can't figure out how to modify the code to allow that port to respond to ping commands. However, and couldn't find any code online in other searches that would do that.
Does anyone know how to use C# to create a firewall rule to allow a port to respond to ping commands?  The app will be deployed in Windows 7 embedded, 64 bit.
Here is some existing code which creates a rule to open a TCP port, which works OK:
private void SetupFirewallAllowIncomingRule(int port)
{
    try
    {
        _log.Debug("Creating instance of Windows Firewall policy (HNetCfg.FwPolicy2)...");
        INetFwPolicy2 firewallPolicy = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")) as INetFwPolicy2;

        if (null == firewallPolicy)
        {
            _log.Error("HNetCfg.FwPolicy2 instance could not be created!");
            return;
        }

        string name = "Rule Port " + port.ToString();

        foreach (INetFwRule2 rule in firewallPolicy.Rules)
        {
            if (name.Equals(rule.Name))
            {
                _log.WarnFormat("Windows Firewall Rule ({0}) already exists. It will not be created again.", rule.Name);
                return;
            }
        }

        _log.Debug("Creating new Windows Firewall Rule (HNetCfg.FWRule)...");
        INetFwRule firewallRule = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")) as INetFwRule;

        if (null == firewallRule)
        {
            _log.Error("HNetCfg.FWRule instance could not be created!");
            return;
        }

        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
        firewallRule.Enabled = true;
        firewallRule.InterfaceTypes = "All";
        firewallRule.Name = name;
        firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;

        //NOTE: Must do this after setting the Protocol!
        firewallRule.LocalPorts = port.ToString();

        _log.DebugFormat("Adding Windows Firewall Rule {0}...", firewallRule.Name);

        firewallPolicy.Rules.Add(firewallRule);

        _log.InfoFormat("Windows Firewall Rule {0} added.", firewallRule.Name);
    }
    catch (Exception ex)
    {
        _log.Error("Windows Firewall Rule could not be added for port " + port.ToString() + "!", ex);
    }
}


text:
Q: Facebook permission : lost right to publish photo and album I've created a facebook app a few weeks ago. The app creates an album, and publish some photo inside. All was worked fine.
Since a few days, it doesn't work anymore.
After trying some (hundreds) tests, it seems :
- app login doesn't show photo upload right anymore,
- i can publish photos in main stream, but it doesn't work as well as before : user need to approve photo and i can't create album.
After looking in app parameters on facebook, all seems normal : permission for photo upload are still there...
Does anyone has any idea about this problem ?
Could it be some matters with review from facebook or something like that ?
Thanks for help !

A: Review is only needed for Open Graph actions and for an app to appear in the app center.

After looking in app parameters on facebook, all seems normal : permission for photo upload are still there...

The permissions set there are for login from the app center only. If you're handling login yourself in your app, you have to ask for permissions via the scope parameter.


text:
Q: Controlling a driverless USB Audio Device I have a USB audio device (Scarlett Focusrite 18i6) which does not require a driver, so I assume it uses the USB HID Audio Class standard.
It works on everything from Windows and Mac to Linux and iOS.
But on Mac and Windows, it has a control application which can for instance enable and disable direct monitoring.
How would I go about reverse-engineering how this is done, so that I can reproduce it on platforms where the control application does not exist?
I'm thinking of booting up Windows in a VMWare session and then logging the USB communication (somehow?) while using the control application, but it does sound tedious considering the amount of data and my very limited understanding of USB.
Any other suggestions?

A: You could try running the control application using Wine instead of reverse engineering it.  However, if it's accessing USB devices then there is a good chance it might be using an API not supported by Wine.
To reverse engineer it, you should find a way to look at the USB traffic between the computer and the device.  Total Phase has some hardware USB protocol analyzers, but you might be able to find a good software solution for free.


text:
Q: Is there a function to retrieve all current logged-in users? Is there a function to retrieve all current logged-in users for Drupal 7?
I tried to build a query based on Get all the logged-in user.
$query->join('users', 'u', 's.uid = u.uid'); //JOIN sessions with users
$query->fields('u',array('name')) //SELECT the fields from node
  ->orderBy('timestamp', 'DESC') //ORDER BY timestamp
  ->range(0,10); //LIMIT to 10 records
  ->execute()
  ->fetchAll();
$result = $query->execute();

I'm still missing something on to retrieve all names from $result as an array, and on how to limit the query to return the users who were active in the last 5 minutes.
I need to put these into an array with their usernames in #title and their user IDs in #href.

A: Retrieve users logged in last 5 minutes :
$users_results = db_query('SELECT u.uid , u.name FROM users u
                   WHERE ( UNIX_TIMESTAMP(NOW()) - u.access ) < (5*60)')
          ->fetchAllKeyed();
dsm($users_results);

EDIT
Like asked :
foreach($users_results as $uid => $name){
  $users[$name] = array('#title' => $name , '#href' => $uid);
}


text:
Q: How can one tell that if $(f\circ x)_u a+(f\circ x)_v b$ is differentiable, then $a,b$ are both differentiable? Here differentiable means indefinitely differentiable. Let $f:U\subset S\to \mathbb{R}$ be any function on a regular surface $S$ differentiable in $U$ and $x:V\subset \mathbb{R}^2\to U\subset S$ be a parametrization of $S$. Note that there need not be $x(V)=U$. My question is that if $a,b:V\to \mathbb{R}$ satisfies that the function $F:V\to \mathbb{R}$ defined by
$$ F(u,v)=(f\circ x)_u a(u,v)+(f\circ x)_vb(u,v)$$
is differentiable in $V$ for all differentiable $f$, then can one conclude that $a,b$ are both differentiable? I  know that if $x(V)=U$ then this is true since we can define $f$ by $f(x(u,v))=u$ or $v$ so that $F=a$ and $F=b$ respectively, but when $x(V)\neq U$ I see no guarantee that such $f|_{x(V)}$ can be extended to a differentiable function over $U$.
The original question I'm working on is Ddo Carmo, section 3-4, Exercise 7.

I encountered this issue when proving that if $w(f)$ is differentiable for all differentiable $f$ then $w$ is differentiable.
Any hint or solution is appreciated. Thanks in advance.

A: You are right that doCarmo does not seem to have thought through this problem at the level of this textbook. You do need the tool of a "bump function," which he does not introduce at this level.
Define
$$\phi(x) = \begin{cases} e^{-1/x}, & x>0 \\ 0, & x\le 0\end{cases}.$$
Then you can check that $\phi$ is smooth, with all derivatives $0$ at $x=0$. Now set $\psi(x) = \dfrac{\int_0^x \phi(t)\phi(1-t)\,dt}{\int_0^1\phi(t)\phi(1-t)\,dt}$. Note that $\psi$ is smooth, $\psi(x)=0$ for $x\le 0$ and $\psi(x)=1$ for $x\ge 1$.
You have a function defined on $V\subset\Bbb R^2$ (namely, $F(u,v)=u$). (Set $B(0,r) = \{u\in\Bbb R^2: \|u\|<r\}$.) Let's assume that $0\in B(0,r)\subset V$ and $x(0)=p$. We will multiply $F$ by an appropriate function $\rho$ that has the properties that $\rho=1$ on $B(0,r/2)$ and $\rho=0$ outside $B(0,r)$. Then the function $(\rho F)\circ x^{-1}$ will extend to be a smooth function everywhere on $U$, which is equal to $f=F\circ x^{-1}$ in a neighborhood of $p$ and $0$ outside $x(B(0,r))$. It remains to build $\rho$ out of $\psi$. Can you do that?


text:
Q: How to replace text in jquery and add formatting I want to replace text with jquery / javascript but with a catch: the text is in bullet format.
The HTML markup would be:

list item 01

list item 02

list item 03

But I have no idea how to utilize this in jquery / javascript other than giving each "li" an id.
I want to do something like this:
function change_text(){
  $("#text_to_be_replaced").text("//I want to format the text in here to
  display in bullet format.");
}

Any advice would be much appreciated! :)

A: Loop each li?
$('#text_to_be_replaced > li').each(function(i) {
   //Do your thang

   //$(this) refers to each of the li being iterated
   $(this).html('new text');

   //i is the iteration index, 0-indexed
});

A: then you can use html instead of text
$("#text_to_be_replaced").html("//I want to format the text in here to
  display in bullet format.");

A: try this
$('#text_to_be_replaced li').each(function() {
    $(this).html('test');
});

A: You can use the .html() method if you want to pass the new contents in one go
function change_text(){
  $("#text_to_be_replaced").html("
 item 1

item 2

item 3
");
}

A: $('#text_to_be_replaced').children('li').each(function(){
     $(this).html('replaced')
});

Use html() and children()

A: Try
function change_text(){
    $("#text_to_be_replaced > li").html(function(index, value){
        return value.replace(/list\s+/, '')
    });
}

Demo: Fiddle


text:
Q: SQLSTATE[23000]: Integrity constraint violation when searching on frontend On my frontend when I type anything in the search box I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'position' in order clause is ambiguous, query was: SELECT `main_table`.`entity_type_id`, `main_table`.`attribute_code`, `main_table`.`attribute_model`, `main_table`.`backend_model`, `main_table`.`backend_type`, `main_table`.`backend_table`, `main_table`.`frontend_model`, `main_table`.`frontend_input`, `main_table`.`frontend_input_renderer`, `main_table`.`frontend_label`, `main_table`.`frontend_class`, `main_table`.`source_model`, `main_table`.`is_global`, `main_table`.`is_visible`, `main_table`.`is_required`, `main_table`.`is_user_defined`, `main_table`.`default_value`, `main_table`.`is_searchable`, `main_table`.`is_filterable`, `main_table`.`is_comparable`, `main_table`.`is_visible_on_front`, `main_table`.`is_html_allowed_on_front`, `main_table`.`is_unique`, `main_table`.`is_configurable`, `main_table`.`apply_to`, `main_table`.`position`, `main_table`.`note`, `main_table`.`is_visible_in_advanced_search`, `main_table`.`is_used_for_price_rules`, `main_table`.`is_filterable_in_search`, `main_table`.`used_in_product_listing`, `main_table`.`used_for_sort_by`, `additional_table`.*, `entity_attribute`.`attribute_id`, IFNULL(al.value, main_table.frontend_label) AS `store_label` FROM `eav_attribute` AS `main_table`
 INNER JOIN `catalog_eav_attribute` AS `additional_table` ON additional_table.attribute_id = main_table.attribute_id
 INNER JOIN `eav_entity_attribute` AS `entity_attribute` ON entity_attribute.attribute_id = main_table.attribute_id
 LEFT JOIN `eav_attribute_label` AS `al` ON al.attribute_id = main_table.attribute_id AND al.store_id = 1 WHERE (main_table.entity_type_id = 4) AND (`entity_attribute`.`attribute_set_id` IN('4')) AND (`additional_table`.`is_filterable` > 0) GROUP BY `entity_attribute`.`attribute_id` ORDER BY position ASC

Now, to overcome this I have amended the getFilterableAttributes() function found in ~/app/code/core/Mage/Catalog/Model/Layer.php to:
     public function getFilterableAttributes()
    {
//        $entity = Mage::getSingleton('eav/config')
//            ->getEntityType('catalog_product');

        $setIds = $this->_getSetIds();
        if (!$setIds) {
            return array();
        }
        /** @var $collection Mage_Catalog_Model_Resource_Product_Attribute_Collection */
        $collection = Mage::getResourceModel('catalog/product_attribute_collection');
        $collection
            ->setItemObjectClass('catalog/resource_eav_attribute')
            ->setAttributeSetFilter($setIds)
            ->addStoreLabel(Mage::app()->getStore()->getId())
            ->setOrder('main_table.position', 'ASC');
        $collection = $this->_prepareAttributeCollection($collection);
        $collection->load();

        return $collection;
    }

This fixes the issue, but now I want to correct the actual problem, I get the error is in laymen terms saying that the position column is present more than once in the query so doesn't know which once to select. But, I cannot see why this is happening. Running the query direct on the database I am able to see position is in the result twice. Would this indicate my database has the position as a duplicate?
Investigating further I found an anomaly, the eav_attribute table seems incorrect, as on a new install I have 17 fields and on my current db I have 33:
New install eav_attribute structure:

Normal installs eav_attribute structure:

A: After careful analysis I have arrived at the following: during a previous update one of the scripts was not successful ran.
In the file:

app/code/core/Mage/Catalog/sql/catalog_setup/mysql4-upgrade-0.7.73-1.4.0.0.0.php

You can see the extra fields I have are moved to a new table called catalog_eav_attributes and removed from eav_attributes.
To correct this, I ran the following alter statement on my database:
  ALTER TABLE `eav_attribute`
  DROP `frontend_input_renderer`,
  DROP `is_global`,
  DROP `is_visible`,
  DROP `is_searchable`,
  DROP `is_filterable`,
  DROP `is_comparable`,
  DROP `is_visible_on_front`,
  DROP `is_html_allowed_on_front`,
  DROP `is_configurable`,
  DROP `apply_to`,
  DROP `position`,
  DROP `is_visible_in_advanced_search`,
  DROP `is_used_for_price_rules`,
  DROP `is_filterable_in_search`,
  DROP `used_in_product_listing`,
  DROP `used_for_sort_by`;


text: Q: On the bounded derived category of a finite dimensional algebra with finite global dimension Let $A$ be a finite dimensional $k$-algebra with finite global dimension. How can I prove that the category $D^b(A)$ (bounded derived category of the category of left finitely generated $A$-modules) is equivalent to $K^b(_AP)$ (bounded homotopy category of complexes made with left projective modules) ?


text:
Q: Typescript duplicate require error in @types/node After attempting to build my first typescript project, I get the following error:
yarn run v1.3.2
$ yarn tsc
$ tsc
node_modules/@types/node/index.d.ts(139,13): error TS2300: Duplicate identifier 'require'.
node_modules/@types/react-native/index.d.ts(8618,14): error TS2300: Duplicate identifier 'require'.

I'm not sure what can cause this error.  I even have node_modules in my exclude in the tsconfig.json. Here are the relevant files:
tsconfig.json
{
  "compilerOptions": {
    "target": "es2015",
    "module": "es2015",
    "moduleResolution": "node",
    "jsx": "react",
    "outDir": "artifacts",
    "rootDir": "src",
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": false,
    "preserveConstEnums": true,
    "allowJs": false,
    "sourceMap": true,
    "noImplicitReturns": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true
  },
  "filesGlob": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ],
  "types": [
    "react",
    "react-native",
    "jest"
  ],
  "exclude": [
    "android",
    "ios",
    "build",
    "node_modules"
  ],
  "compileOnSave": false
}

package.json dependencies
  "dependencies": {
    "react": "16.0.0",
    "react-native": "0.51.0"
  },
  "devDependencies": {
    "@types/jest": "^22.0.1",
    "@types/react": "^16.0.34",
    "@types/react-native": "^0.51.9",
    "babel-jest": "22.0.4",
    "babel-preset-react-native": "4.0.0",
    "concurrently": "^3.5.1",
    "jest": "22.0.4",
    "react-test-renderer": "16.0.0",
    "rimraf": "^3.6.2",
    "tslint": "^5.8.0",
    "typescript": "^2.6.2"
  },


text:
Q: How to include a lot of decision making loops for checking a number within a range in a correct way? I am trying to solve a question to generate a list of numbers from a given range by making each number passed through a set of rules to get that number added in the list. Also to find the maximum element from the list.
This is the actual question:
Write a python program which finds the maximum number from num1 to num2 (num2 inclusive) based on the following rules.

*

*Always num1 should be less than num2

*Consider each number from num1 to num2 (num2 inclusive). Populate the number
into a list, if the below conditions are satisfied
a)Sum of the digits of the number is a multiple of 3
b)Number has only two digits
c)Number is a multiple of 5

*Display the maximum element from the list

In case of any invalid data or if the list is empty, display -1.
First of all, I am new to Python and not familiar to solve these type of complex problems. So I think I made a lot of silly mistakes.
def find_max(num1, num2):

    max_num=-1
    num_list=[] #list declared
    if(num1<num2): #to check num1 < num2 as said in the question
        for numbers in range(int(num1),int(num2)+1): #for numbers from the range
            tot=0
            count=0
            while(numbers>0):
                digit=numbers%10
                tot=tot+digit #to generate sum of digits
                numbers=numbers//10
                count=count+1 #to count the number of digits
                if(tot%3==0 and count==2 and numbers%5==0):
                    num_list.append(numbers) #to generate the list
                else:
                    print(-1)
    else:
        print(-1)
    max_num = max(num_list) #to find the maximum value in the list
    return max_num

#Provide different values for num1 and num2 and test your program.
max_num=find_max(10,15)
print(max_num)

Results I am getting :
-1
-1
-1........

A: Your function is not working like you want because you are using numbers for checking condition, but you're changing it in your code when you are making computations.
numbers = numbers // 10

So when you'll use it in if block, numbers will have a different value not the initial one.
For example with numbers = 15 at the start it will become:

numbers -> 15 -> 1 -> 0

Thus when you check numbers % 5 == 0 it will never pass and the if conditional will fail. Use a copy of the number and every thing will work fine.
Revisited code:
def function_name(num1,num2):
  num_list=[] #list declared

  if(num1<num2): #to check num1 < num2 as said in the question
      for numbers in range(int(num1),int(num2)+1): #for numbers from the range
        tot=0
        count=0
        copy = numbers
        while(copy>0):
            digit=copy%10
            tot=tot+digit #to generate sum of digits
            copy = copy//10
            count = count+1 #to count the number of digits
            if(tot%3==0 and count==2 and numbers%5==0):
                num_list.append(numbers) #to generate the list
            else:
                print(-1)
  else:
      print(-1)
  if num_list:#if the list is populates with some numbers
    return max(num_list)
  else: return "what you think is needed in case there aren't numbers" #None is a good choice equivalent to null in other programming languages

print(function_name(10,15))

My idea to implement your function
Not the best, but its shorter and more readable.
def function_name(num1,num2):
  num_list=[] #list declared

  if(num1<num2): #to check num1 < num2 as said in the question
      for number in range(int(num1),int(num2)+1): #for numbers from the range

        # for every char return its int and group all in a list
        # [int(digit) for digit in str(number)]
        tot = sum( [int(digit) for digit in str(number)])

        #count how many char are that is like saying how many digits
        count= len(str(number))

        if(tot%3==0 and count==2 and number%5==0):
            num_list.append(number) #to generate the list
        else:
            print(-1)
  else:
      print(-1)
  if num_list:#if the list is populates with some numbers
    return max(num_list)
  else:
    return "what you think is needed in case there aren't numbers" #None is a good choice equivalent to null in other programming languages

print("Max", function_name(10,15))

A: The mistake in your code is that in your 'while' loop, you're modifying the value which is being checked for the conditions. (lulian has explained this well.)
Actually, your code can be rewritten more simply. You have these requirements. (a) Sum of the digits of the number is a multiple of 3. (b) Number has only two digits (c) Number is a multiple of 5.
Requirements (a) and (c) can be combined into a single requirement: if you know middle school mathematics, (a) basically means that the number itself is divisible by 3, and (c) means that it is divisible by 5. Together, they mean that the number should be divisible by 3 times 5, i.e. 15. We can exploit this property.
Let us revisit the problem. Observe that each time invalid data is detected, I use a return statement.
def find_max(num1, num2):

    # check for invalid data: 'num1' and 'num2' should be integers
    if type(num1) != int or type(num2) != int:
        return -1

    # check if 'num1' is greater than 'num2'
    if num1 > num2:
        return -1

    # initialize empty list
    num_list = []

    # find the nearest multiple of 15 to 'num1'
    if num1 % 15 == 0:
        nearest_multiple = num1
    else:
        nearest_multiple = num1 + 15 - num1 % 15

    # scan through possible numbers from 'nearest_multiple' to 'num2'
    for numbers in range(nearest_multiple, num2 + 1, 15):
        if 10 <= numbers <= 99 or -99 <= numbers <= -10:
            num_list.append(numbers)

    # if no valid number was detected, the list will remain empty
    if num_list == []:
        return -1

    return max(num_list)

Explanation:
First, locate the nearest multiple of 15 greater than or equal to num1. So, if num1 is 15, then nearest_multiple is also 15. But if num1 were 21, then nearest_multiple would be 30. (The formula used is pure math.)
Then, we iterate from nearest_multiple to num2 in jumps of 15. That way, we encounter only numbers which satisfy both (a) and (c). Then we check the number we encounter for condition (b).

A: def find_max(num1, num2):
if (num1<num2):

    max_num=-1
    for i in range(num1,num2 + 1,1):
        if (10 <= i <= 99 or -99 <= i <= -10):
            j = i/10
            k= i%10
            if ((j+k)%3==0 and i%5 == 0):
                max_num = i
# Write your logic here
    return max_num
else:
    return -1

#Provide different values for num1 and num2 and test your program.
max_num=find_max(-100,500)
print(max_num)

A: def find_max(num1, num2):

max_num=-1
num_list=[]
if(num1<num2):
    for numbers in range(int(num1),int(num2)+1):
        tot=0
        count=0
        while(numbers>0):
            digit=numbers%10
            tot=tot+digit
            numbers=numbers//10
            count=count+1
            if(tot%3==0 and count==2 and numbers%5==0):
                num_list.append(numbers)
            else:
                print(-1)
else:
    print(-1)
max_num = max(num_list)
    return max_num

max_num=find_max(10,15)
print(max_num)


text:
Q: How to access file upload selected file without changing page using javascript? I need to create a file upload field which I have below:

    File Upload
    <input type="file" id="file-upload"/>

How do I access the contents of the selected file without going to another page or adding anything to the URL in Javascript?

A: Use this simple code

var inputFile = document.getElementById("file-upload");

inputFile.addEventListener("change", function(){
    var files = inputFile.files;
    console.log(files[0]);
    alert(files[0].name);
});
<input type="file" id="file-upload"/>


text:
Q: Have you encountered this issues during the installation process process of OpenGauss on openEuler? Have you ever encountered it? How can it be solved [root@localhost script]# ./gs_preinstall -U omm -G dbgrp -X /opt/software/openGaussInstall/openGaussInstall.xml
Warnging version of python doesnot meet the expection, maybe third-party libs need to be compiled by yourself
Failed to execute cmd: rm -rf '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_linux.so' && cp -r '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_linux.so_3.9' '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_linux.so' && rm -rf '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_posix.so' && cp -r '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_posix.so_3.9' '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_posix.so' . Error:
cp: cannot stat '/opt/software/openGaussInstall/script/gspylib/common/./…/…/…/lib/psutil/_psutil_linux.so_3.9': No such file or directory
Get the right answer

A: "Warnging version of python doesnot meet the expection"
Carefully read the requirements for the operating system version and the python version in the openGauss database installation document. If it is openEuler 22.03 LTS, then you need the latest version of the OM source code, this is the recently added support of this system


text:
Q: Is there a good practice approach to powering down peripheral devices (SPI, I2C, UART) which use significant power? I'm trying to limit the power usage of a system which uses a number of sensors and transceivers on SPI, I2C, and UART buses. I can't easily design around the sensors in use, so selecting devices with explicit shutdown modes or low quiescent current is unfortunately not an option. Some of the devices (an ESP8266 for example) offer low-power modes which are sufficient, but others do not.
The devices are varied in function: voltage/current/power sensing, temperature and humidity sensing, MEMS, transceivers.
In a question discussing unpowered I2C devices, I understand that there are some difficulties with switching off these devices entirely, due to potential parasitic effects on the bus.
One option I looked at is to insert a bidirectional galvanic isolator at the SDA pin of each I2C device that I wish to unpower, though I have concerns about propagation delay - would I need to drive the clock pin through another channel to ensure a delay match? This could quickly become expensive to implement, too, since the isolator ICs aren't the cheapest of ICs.
This still leaves me without much information on potential parasitic effects on SPI and UART buses from unpowered devices. Do these have similar problems? I'm also unsure as to the best way to actually disconnect the device from the power - is a single N-channel MOSFET inline with the device's Vcc (or equivalent) pin appropriate?

A: I would use an analog multiplexer as shown below:

Use the select line to connect the master side (on the left) to the device (on the right) when it is powered up; select the dummy lines (which can go nowhere) to connect to the master and then power the device down.
The multiplexer will provide isolation.
The device may need a pullup (high value, it is not there for any reason except to put a valid level on the pins) on SDA and SCL.

A: Off devices with SDA and SCL pulled up to a power rail which is on, will leak current to the SDA and SCL pins of off device, so you need to isolate them.
I would use an analog switch to isolate the I2C lines to the device before turning it off.
You will need to have voltage rails (2 atleast here, one for master and one for device) with same voltage level to maintain logic compatibility between device and master.


text:
Q: Копировать и вставить файл в android Здравствуйте. На карте памяти есть файл file.txt. Как с помощью Java переместить его в другую папку? То есть сейчас файл в папке FolderA, а нужно, чтобы он оказался в папке FolderB.
File source = new File(Environment.getExternalStorageDirectory().getPath() + "/FolderA/file.txt");
File destination = new File(Environment.getExternalStorageDirectory().getPath() + "/FolderB/file.txt");

Нужно сделать что-то вроде того:
CopyFile(source, destination);
public void CopyFile(File ОТКУДА, File КУДА) {...}

A: public void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}


text:
Q: Using InstallShield, where to place "all user" accessible data files I'm creating an installer using InstallShield. v 11.5. Somewhat new territory. There's data files that need to be read/write for all users. The main concern is permissions for Vista and 7. I assume there's a standard location path to query. I'm not sure how to do this from within InstallShield. Perhaps does "Program Files/Common Files" map automatically to the correct path on the users system? I just need to be pointed in the right direction to find the answers I need. As a bonus, there's a .ini file that needs to be updated with that folder path. Any help is much appreciated.
edit: If it's done via the 'Script-defined Folders', such as CommonAppDataFolder, how is that setup?

A: You probably want to put the files in C:\ProgramData\[YourCompanyName]\
There will be security issues with Windows 7 if the application is trying to write files in the 'Program Files' directory without administrator privileges.
In the latest versions of InstallShield, the [CommonAppDataFolder] predefined variable resolved to C:\ProgramData on Windows Vista and 7. It would be something else for Windows XP.


text:
Q: Open Design Alliance Drawings SDK in Excel VBA I am not very familiar with VBA, only access database stuff. But I was tasked with updating a CAD drawing application written in Excel VBA using the latest version of Open designs drawing SDK.
It is still working with the previous version of TeighaX library. But when I reference the newer version of the TeighaX library it doesn't work.
An example of one of the functions below.
Function funOpen_CAD_File(File_To_Open As Range, OpenDrawing As IAcadDocument, Optional Message As String) As Boolean
'
'Opens a CAD file. funOpen_CAD_File = True if the file opened OK
'
'Argument 1 = A single cell range containing the full path and name for the file to be opened
'Argument 2 = The IAcadDocument variable to open the drawing into
'Message = An optional text string that returns the document type and or erroe message
'
'If the CAD file cannot be opened, the range (Argument 1) is coloured Orange
'
'Other file types are coloured also.
'
'

    Dim sFilename As String
    Dim nErrorCellColourIndex As Integer
    Dim nNonDWGFileCellColour As Integer
    Dim objTeighaHost As TeighaX.OdaHostApp
    Dim objTeighaApp As TeighaX.AcadApplication

    funOpen_CAD_File = True
    sFilename = File_To_Open
    nErrorCellColourIndex = 3
    File_To_Open.Interior.ColorIndex = xlNone
    Message = "File OK"

    If LCase(Right(sFilename, 4)) = ".dwg" Then

            Set objTeighaHost = CreateObject("TeighaX.OdaHostApp")
'            Set objHost = New OdaHostApp
            Set objTeighaApp = objTeighaHost.Application

                'Some drawings can be broken - Check for this
                On Error GoTo ErrorTrap
                    Set OpenDrawing = objTeighaApp.Documents.Open(sFilename, False)
                On Error GoTo 0

            objTeighaApp.Quit
            Set objTeighaApp = Nothing
            Set objTeighaHost = Nothing

    Else

        funOpen_CAD_File = False

        Select Case LCase(Right(sFilename, 4))

            Case ".xls", "xlsx", "xlsm"
                Message = "Excel File"
                File_To_Open.Interior.ColorIndex = 22

            Case ".doc", "docx", "docm"
                Message = "Word Document"
                File_To_Open.Interior.ColorIndex = 44

            Case ".pdf"
                Message = "PDF Document"
                File_To_Open.Interior.ColorIndex = 8

            Case ".jpg", ".bmp", ".tif"
                Message = "Image File"
                File_To_Open.Interior.ColorIndex = 36

            Case Else: Message = "Not a CAD File"
                Message = "Undefined Doc Type"
                File_To_Open.Interior.ColorIndex = 15

        End Select

    End If

Exit Function

ErrorTrap:

    funOpen_CAD_File = False
    File_To_Open.Interior.ColorIndex = nErrorCellColourIndex
    Message = "Faulty File - " & Err.Description
    Resume Next

End Function

The errors:
Run-Time error '429':
ActiveX component can't create object

and
License information for this component not found. You do not have an appropriate license to use this functionality in the design environment.


text:
Q: Our source of information was the spies captured during the raid. - Why is it ok for "spies" to be plural when subject/verb is singular?
Our source of information was the spies captured during the raid.

Subject singular, helping verb singular then how come spies being plural fits in here?
Suggestions please.

A: There's no requirement in English that the object of a sentence match the number of the subject or the verb.
For example...

I have cats.

The subject is singular, the verb is singular but the object is plural.
Yes, "spies" are the "source of information"... and you can rephrase it as such:

The spies captured during the raid were our source of information.

Now the subject and verb are plural but the object is singular.

So, if you have several spies, why is it only one "source of information"... because they are being treated as a single group of people, and that group makes up a single "source". This is a choice by the author of the sentence.
It's perfectly acceptable to consider each spy captured during the raid as a single source:

Our sources of information were the spies captured during the raid.
  The spies captured during the raid were our sources of information.

Both of these are fine, they're just not what the author chose, though I personally prefer the original in this case.


text:
Q: Showing $\int_{-\infty}^{\infty}\frac{x^3\sin{x}\;dx}{x^4+5x^2+4} = \frac{(4-e)\pi}{3e^2}$ via contour integration I have a complex integral $I$ to solve to show that
$$I=\int_{-\infty}^{\infty}\frac{x^3\sin{x}\;dx}{x^4+5x^2+4} = \frac{(4-e)\pi}{3e^2}$$
I know that you can integrate over the contour of a semicircle where and represent sin as an infinite sum but not sure what to do next. Should the polynomial be converted to a partial fraction too?

A: On a canonical semicircle of radius $\;R>0\;,\;\;C: \{z\in\Bbb C\;|;|z|=R\;,\;\;\text{Im z}>0\}\;$ , we get
$$\left|\int_C\frac{z^3\,e^{iz}}{z^4+5z^2+4}\right|\le \max_{z\in C}\frac{|z|^3|e^{iz}}{|z^4+5z^2+4}\,\cdot \ell(C)\le\frac{R^3\,e^{-\text{Im}\,z}}{R^4-5R^2-4}\cdot\pi R\xrightarrow[R\to\infty]{}0$$
since exponential kills polynomial and $\;e^{-\text{Im}\,z}\xrightarrow[R\to\infty]{}0\;$ because $\;\text{Im}\,z>0\;$ and $\;\text{Im}\,z\to\infty\;$ when $\;R\to\infty\;$ ...You could use Jordan's Lemma
Thus, if $\;D\;$ is the contour $\;C\cup [-R,R]\;$ (the semicircle and the diameter  from $\;-R\;$ to $\;O\;$ in the real axis), you get
$$2\pi\left[\sum \text{Res}(F,z_k)\right]=\oint_D\frac{z^3\,e^{iz}}{z^4+5z^2+4}dz=\int_{-R}^R\frac{x^3\,e^{ix}}{x^4+5x^2+4}dx+\int_C\frac{z^3\,e^{iz}}{z^4+5z^2+4}dz$$
and on passing to the limit $\;R\to\infty\;$ you get your real improper integral on the right, and its value on the left.
Also, for the singularities (in fact, simple poles in this case so the residue is easily calculated):
$$z^4+5z^2+4=(z^2+1)(z^2+4)=(z-i)(z+i)(z+2i)(z-2i)\ldots\text{ and etc.}$$
Last thing: by Euler, $\;e^{ix}=\cos x+i\sin x\;$ , so you get two improper integrals, one of the real part , and the other a purely imaginary one (which is your integral). Figure out what happens here (further hit: odd and even functions)

A: Using @EeveeTrainer's tips, $I=\Im w$ with$$\begin{align}w&:=\int_{\Bbb R}\frac{z^3e^{iz}dz}{(z^2+1)(z^2+4)}\\&\stackrel{\star}{=}2\pi i\left(\left.\tfrac{z^3e^{iz}}{(z+i)(z^2+4)}\right|_{z=i}+\left.\tfrac{z^3e^{iz}}{(z+2i)(z^2+1)}\right|_{z=2i}\right)\\&=2\pi i\left(\tfrac{-1}{6e}+\tfrac{2}{3e^2}\right)\\\implies I&=\frac{(4-e)\pi}{3e^2},\end{align}$$where $\stackrel{\star}{=}$ uses a semicircle in the half-plane $\Im z>0$ (@DanAntonio's answer verifies that the contour integral along the arc vanishes in the infinte-radius limit).

A: $$\frac{x^3}{x^4+5x^2+4}=\frac{x^3}{(x^2+4)(x^2+1)}=\frac43\frac{x}{x^2+4}-\frac13\frac{x}{x^2+1}$$
then you could maybe split this up further:
$$x^2+4=(x+2i)(x-2i)$$
$$x^2+1=(x+i)(x-i)$$

$$\frac43\frac x{x^2+4}=\frac23\frac1{x+2i}+\frac23\frac1{x-2i}$$
$$\frac13\frac x{x^2+1}=\frac16\frac1{x+i}+\frac16\frac1{x-i}$$
and so:
$$\frac{x^3}{x^4+5x^4+4}=\frac23\frac1{x+2i}+\frac23\frac1{x-2i}+\frac16\frac1{x+i}+\frac16\frac1{x-i}$$


text:
Q: Java jmxremote not opening port I've made a hello world java program to test how jmxremote works:
public class Main {
    public static void main(String argv[]) {
        try {
            System.out.println("Press  to continue...");
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

compiled it with javac Main.java, and run it like

java -Dcom.sun.management.jmxremote \
     -Dcom.sun.management.jmxremote.port=9010 \
     -Dcom.sun.management.jmxremote.local.only=false \
     -Dcom.sun.management.jmxremote.authenticate=false \
     -Dcom.sun.management.jmxremote.ssl=false \
     Main

However the port never gets opened:
# telnet localhost 9010
Trying ::1...
telnet: connect to address ::1: Connection refused

(nc -l and netstat show same results). Java version is
java version "1.5.0"
gij (GNU libgcj) version 4.4.7 20120313 (Red Hat 4.4.7-4)

and OS is Centos 6.5 (java installed from default repo with yum).
How do I fix this?
I've tried messing up the option names, but never got any info about an error - is jmx even available in java 1.5?

A: Like peoples say, libgcj is not a very good idea. It was a poor try from GNU peoples to fork a GPL licensed JVM that will compile java code to machine code, not byte code. It's now a dead project that never supported JMX.
A yum install java-1.7.0-openjdk-devel will provide what you need.


text:
Q: I am trying to append active state to this hamburger Button I am trying to append active state to this hamburger icon to get an animation but it is not working. I have been on google all day trying to figure this out. Can someone please helpme. the hamburger icon needs to toggle between active state to animate in and out i realized doing this through javascript will break the app. so i added some state and this still isnt working someone, please help
I can use the button with id hamburger or use
<Slider/> component imported/
import React, { Component } from "react";
import { Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import { ButtonContainer } from "./Button.jsx";
import { Slider } from "react-burgers";

export default class Navbar extends Component {

  constructor(props) {
        super(props);
        this.state = {active: false};
    }

    click() {
        this.setState({active: true});
    }

  render() {
    // OnScroll Hide
    var prevScrollpos = window.pageYOffset;
    window.onscroll = function() {
      var currentScrollPos = window.pageYOffset;
      if (prevScrollpos > currentScrollPos) {
        document.getElementById("navbar").style.top = "0";
      } else {
        document.getElementById("navbar").style.top = "-50px";
      }
      prevScrollpos = currentScrollPos;
    };

    return (

        <Link to="/" className="nav-link text-capitalize text-warning">
          home
        </Link>
        <button
          className="navbar-toggler  "
          type="button"
          data-toggle="collapse"
          data-target="#navbarTogglerDemo02"
          aria-controls="navbarTogglerDemo02"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >

        </button>
        <button
          id="hamburger"
          onClick={this.click.bind(this)}
          className="hamburger hamburger--collapse  bg-warning "
          type="button"
        >

        </button>

                Products

                <Link
                  to="/clothing"
                  className="dropdown-item text-center  bg-black"
                >
                  Clothing
                </Link>
                <Link
                  to="/gadgets"
                  className="dropdown-item text-center  bg-black"
                >
                  Gadgets
                </Link>
                <Link
                  to="/smoke"
                  className="dropdown-item text-center  bg-black"
                >
                  Head Shop
                </Link>

            <Link to="cart" className="ml-auto border-none">
              <ButtonContainer>

                  {/* (0) */}

              </ButtonContainer>
            </Link>

    );
  }
}


text:
Q: Question "stuck" in intersite limbo I put a question on site A, where is was closed (on hold currently) as off topic and belonging to site B. So I posted it to site B, where it was again closed as "off topic, should be on site A".
How to resolve this? While the nature of the issue in question might be either medical or linguistic, I don't know that until I get an actual answer.
The questions:
(health) https://health.stackexchange.com/questions/5341/why-is-salt-being-referred-to-as-sodium
(english) Why is salt being referred to as "sodium"?

A: In the general case, when you're unsure whether a question belongs in one domain or another, just ask in chat on one of the sites, before posting your question. People there should be able to help you formulate your question, and guide you as to where it belongs.
In this specific case, it seems to me that the actual question you care about does belong on Health.SE. The question just needs some radical editing.
I think your underlying question is something like:

I notice that on food labels, instead of listing the amount of salt present, they list the amount of sodium. Is that because the health risk of too much or too little salt intake, derives entirely from the sodium? That is, is the chloride not really relevant to health, it's the sodium, and there are other sources of sodium in food in addition to salt? Why is "salt" referred to as "sodium" in nutrition facts (on food products) and similar documents?

As it happens, there are indeed linguistic and chemistry aspects to your question too, and a good answer should pick up on those as well as the health element.

A: It is not on-topic for EL&U. (Pardon me while I take umbrage.) It is not about word choice and usage so much as it is about food labeling practices, which are not on-topic on our site.
That said, your question in its current form also does not show sufficient research for EL&U word choice type questions. At minimum, you would need to define each term that you find confusing and explain why you are having trouble understanding the difference between the terms.

A: In a general case I fully agree with EnergyNumbers' answer. Another solution would be to flag your own question and ask the moderators to check if it would be more suitable for another (suggest which) site, and if yes to ask them to migrate it.
However, in this case:
A. The OP repeatedly refuses to do research. At health SE they even don't edit to include links provided for them by other users in comments; on EL&U the question is heavily edited by other users to add research.
B. The OP refuses guidance how to make the question more on topic for the site where the question is already posted (on health SE provided by me)
C. The OP doesn't know what they want. Are they interested in health implications of omitting chloride from the sodium-chloride name? In etymology of sodium or usage of the word sodium? Whether there is a rule or historical development that shows if and why would a chemical name be shortened from sodium-chloride to just sodium?
How can we answer a question when the OP doesn't know what it is that they want to ask?

A: It definitely doesn't belong in health. It appears to be totally on topic for English. From the help center: "Word choice and usage" is on topic. I'd ask on their meta why your question doesn't apply.
I've left a comment on the question @-ting at one of the closers making my case.  They may explain nuances I'm not catching, or they may agree and vote to reopen.


text:
Q: Why does the following code for switching the visibility of two containers not work and what is the correct way of doing it? I am trying to make a button that makes a box visible or invisible depending on the state of another box. Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[
            public function switchContainers():void {
                if ((screen1.visible = false) && (screen2.visible = true)) {
                    screen2.visible = false;
                    screen2.includeInLayout = false;
                    screen1.visible = true;
                    screen1.includeInLayout = true;
                } else {
                    screen1.visible = false;
                    screen1.includeInLayout = false;
                    screen2.visible = true;
                    screen2.includeInLayout = true;
                }
            }
        ]]>
    </fx:Script>

    <s:SkinnableContainer id="screen1" width="100%" height="80%" backgroundColor="red" visible="false" includeInLayout="false" />
    <s:SkinnableContainer id="screen2" width="100%" height="80%"  backgroundColor="blue" visible="true" includeInLayout="true" />
    <s:Button top="5" left="5" label="Switch containers" click="switchContainers()"/>

</s:Application>

Whenever I click the button, nothing happens. I only get to see the blue container. Why doesn't this work?
The ultimate aim of this exercise is to get to display different "screens" in an application (a login screen, a menu screen, etc.) without resorting to ViewStack (I'm trying to use exclusively Spark components). What is the preferred way of doing this?

A: In your conditional statement, you're using an assignment operator (=) instead of an equality operator (==) when evaluating visibility of screens.
if ((screen1.visible = false) && (screen2.visible = true)) {}

Change this to an equality expression:
if ((screen1.visible == false) && (screen2.visible == true)) {}

Another method to accomplish this is to use Flex state system, in which you would define states of screen1 and screen2:
<s:states>
    <s:State name="screen1"/>
    <s:State name="screen2"/>
</s:states>

Use the includeIn property to include a component:
<s:SkinnableContainer id="screen1" includeIn="screen1" />
<s:SkinnableContainer id="screen2" includeIn="screen2" />

Then, change state using the changeState property:
currentState = "screen2";

A: In your if condition, you use the operator = (assignment) which assigns a value to a variable, instead of the operator == (equality) which tests two expressions for equality. Your condition should be written like this :
if ((screen1.visible == false) && (screen2.visible == true)) {}


text:
Q: How to remove Bitmap from ArrayList? I have a class called PlayerList, in in that class i have an ArrayList defined like this :
private ArrayList<Bitmap> images = new ArrayList<Bitmap>();

Now, an ArrayList remove method can exept 2 arguments, an index and an Object.
I'm trying to remove a Bitmap from the array by sending the Bitmap to it. The thing is the bit map is made of the same image but the instace of the Bitmap i saved in the array is not the same i'm trying to find, when i print the ArrayList to console i see new names all the time, stuff like :
[android.graphics.Bitmap@44ea2d48, android.graphics.Bitmap@44ea2e20]

Could this be related? and while wer're at it, The class implements Parcelable so the data being read/writen back and forth, that can't be too healthy too, right?
Am i missing a generic problem or it's code specific and i should publish my code?
My problem here basiclly is when i try to remove the Bitmap, it allways removes the wrong item in the arraylist, always 1 before the 1 i need

A: Unless you have a handle to the BitMap's hash code or a like key based on which it is stored, you can't remove a desired one from the list. If you just want to depend on BitMap stored, you need to traverse through the list and parse elements to find desired bitmap. Again you need a hascode to identify if the BitMap you are parsing is what you are looking for. Meaning you need to maintain a list of hashcode's for each of the BitMap stored. Alternatively use HashMap over List that allows to store a key against a BitMap being stored. And you can process your requirement based on the key and use it whenever required to remove a BitMap from the HashMap table.
HashMap<String, BitMap> myBitMaps = ... // construct as you desire.
...
if ( condition satisfied on key ) {
  myBitMaps.remove( keyObject );
  // process further
}


text:
Q: How can I make websites that use non-latin UTF-8 fonts viewable in iOS Whenever I open webpages (created by other people) that contain custom fonts (non-latin), all I see is square boxes.  This is of course because the required fonts are

*

*Not one of the many fonts that come with iOS

*The person who created the website did not embed the custom font in the webpage so the site can be viewable in iOS

So I am trying to create an App that allows me to somehow tell UIWebView to use my custom font if the webpage contains certain unicode characters. Of course, I will have to include the custom font in the app resources directory.


text:
Q: Is there a statement to calculate the time difference between the reading in the database? i am trying to make RFID access control with 2 readers as something similar to a two factor authentication system.
I have been trying to calculate the time difference between two timestamps from different RFID readers in the database. I have tried many different ways to query the results, but keep getting a zero or errors.
I have tried several query commands to calculate the time difference ex:timestampdiff with various combinations. I have shown some of the ones I've tried.
   SELECT COUNT(*) FROM tag_logs
   WHERE tag_logs = tag_no
   BETWEEN timestamp ('timestamp', 'timestamp');

SELECT *
FROM tag_logs
WHERE timediff is BETWEEN (MINUTE_SECOND,'timestamp', 'timestamp' )

I expected the output to calculate the number of rows and check if it is equals to greater than a specific number.

A: You can use the MySQL TIMEDIFF function:

From a quick google search:

The MySQL TIMEDIFF() function returns the difference between two time or datetime values. The way it works is, you provide the two values to compare, and TIMEDIFF() subtracts the second value from the first, then returns the result as a time value.

EDIT:
After rethinking your problem, it seems evident that your task is more complex than it seems at first glance. If you want to check the difference between two RFID accesses, it's a lot more difficult. If you want to query for all the records between one time and another, it's a lot less difficult. Your first example:
SELECT COUNT(*) FROM tag_logs
WHERE tag_logs = tag_no
BETWEEN timestamp ('timestamp', 'timestamp');

is only going to add the values of the two timestamps, which is going to result in a date more than twice as far from the unix epoch as we are now; and since you haven't supplied a second value for the between keyword, it's going to choose that to be 00:00:00 (0 epoch-time, 1st of January 1970), and every record will be returned.
Your second example:
SELECT *
FROM tag_logs
WHERE timediff is BETWEEN (MINUTE_SECOND,'timestamp', 'timestamp' )

doesn't exactly make too much sense either. I see where you're going with this, but it seems thrown together from examples on the internet. What you want is probably something like this:
SELECT *
FROM tag_logs
WHERE timestamp BETWEEN timestamp1 AND timestamp2.

You seem to want to calculate the time difference though for each record though.
What you want is something that would go row-by-agonizing-row and calculate the timestamp difference between the two records:
SELECT COUNT(*)
FROM  (SELECT p1.id,
       p1.time,
       TIMEDIFF(p2.time, p1.time)
           AS timedifference
       FROM tag_logs p1
       INNER JOIN tag_logs p2
       ON p2.id = (p1.id + 1)
ORDER BY p1.id ASC) time_table
WHERE time_table.timedifference >= '00:05:00'

Here is a functioning SQL fiddle for example
And try #2!
SELECT COUNT(*)
FROM (SELECT p1.id, p1.ts, TIMEDIFF(timestamp(p2.ts), timestamp(p1.ts)) AS timedifference
       FROM tag_logs p1
       INNER JOIN tag_logs p2
       ON p2.id = (p1.id + 1)
ORDER BY p1.id ASC) time_table
WHERE TIME_TO_SEC(time_table.timedifference) >= TIME_TO_SEC('00:10:00')

And another SQL Fiddle!
37 iterations later....
SELECT COUNT(*)
FROM (SELECT p1.id, p1.ts, UNIX_TIMESTAMP(p2.ts) - UNIX_TIMESTAMP(p1.ts) AS timedifference
       FROM tag_logs p1
       INNER JOIN tag_logs p2
       ON p2.id = (p1.id + 1)
ORDER BY p1.id ASC) time_table
WHERE time_table.timedifference >= TIME_TO_SEC('1:00:00')


text:
Q: how to set ng-model Value via ng-init or value tag I want to set ng-model Value. I tried with ng-init and value tag.
My code:
Init
{{formObject.consultantId}}  // value prints

<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id=formObject.consultantId">

{{formObject.consultant.id}} // no data Prints

Value
{{formObject.consultantId}}  // value prints

<input type="hidden" data-ng-model="formObject.consultant.id" value="{{formObject.consultantId}}">

{{formObject.consultant.id}} // no data Prints

This works for me
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id='test'">

{{formObject.consultant.id}} // prints as test

Whats wrong in my code ?  How to initialize this Value to Model ?
EDIT
I found my issue. This code works for me in Normal Html Form.
But above codes are in ModelForm(directive).

A: you should change {{formObject.consultantShare.consultant.id}} to {{formObject.consultant.id}} (to OP's edit, now removed)
Take a look at this

var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {
    $scope.formObject = {};
    $scope.formObject.consultant = {};
    $scope.formObject.consultantId = "254";

});

{{formObject.consultantId}} // value prints
    <input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id=formObject.consultantId" />{{formObject.consultant.id}}

{{formObject.consultantId}} // value prints
    <input type="hidden" data-ng-model="formObject.consultant.id" value="{{formObject.consultantId}}"/>{{formObject.consultant.id}}

A: Can you share your controller to see how formObject is initialized. Meanwhile I have added

var myapp= angular.module('myForm',[]);

(function(){

angular.module('myForm').controller('formController',[formController]);

function formController(){
  var vm = this;
  vm.formObject = {consultantId:10,consultant:{consultantId:''}};
  }

})();
<!DOCTYPE html>

      <link rel="stylesheet" href="style.css">

      formObject.consultantId:{{vm.formObject.consultantId}}
      <input type="hidden" ng-model="vm.formObject.consultantId" ng-init="vm.formObject.consultant.consultantId=vm.formObject.consultantId"

      formObject.consultant.consultantId: {{vm.formObject.consultant.consultantId}}

my solution at : http://plnkr.co/edit/q4d8ZVXz3ki02EjkNZ0n