text:
Q: Lagrange's theorem I don't understand left coset and Lagrange's theorem... I'm working on some project so please write me anything what could help me understand it better

A: Suppose $G$ is a group, and $H$ is any subgroup of $G$. I would like to try to define something similar to "congruence modulo $n$" for integers, but for this arbitrary group $G$ and subgroup $H$.
In the integers, we say that $a\equiv b\pmod{m}$ if and only if $a-b$ is an element of the subgroup $m\mathbb{Z}$. So we are going to try something similar for $H$ and $G$, taking into account that $G$ need not be abelian.
I'm not going to assume the group is finite until I say so explicitly.
Definition. Let $G$ be a group and let $H$ be a subgroup. If $x,y\in G$, we say that $x$ and $y$ are congruent on the right modulo $H$ if and only if $xy^{-1}\in H$. We write this $x\equiv_H y$.
Proposition. $\equiv_H$ is an equivalence relation on $G$.
Proof. We need to show that the relation is reflexive, symmetric, and transitive. Let $x\in G$. Then $xx^{-1} = e\in H$ (since $H$ is a subgroup, hence contains $e$), so $x\equiv_H x$.
Now let $x,y\in G$, and suppose that $x\equiv_H y$; we want to show that $y\equiv_H x$ holds as well. Since $x\equiv_H y$, then $xy^{-1}\in H$. Since $H$ is a subgroup, it is closed under taking inverses, so $(xy^{-1})^{-1} = (y^{-1})^{-1}x^{-1} = yx^{-1}\in H$. By defintion, this means that $y\equiv_H x$, as desired.
Finally, suppose that $x,y,z\in G$ and that $x\equiv_H y$ and $y\equiv_Hz$. We want to show that $x\equiv_H z$. The first congruence implies $xy^{-1}\in H$; the second that $yz^{-1}\in H$. Since $H$ is a subgroup, it is closed under products, so $(xy^{-1})(yz^{-1})=xz^{-1}\in H$, hence $x\equiv_H z$, as desired. QED
Notice that the three basic properties of a subgroup are precisely needed for the three basic properties of an equivalence relation: $H$ contains the identity is used for reflexivity; $H$ is closed under inverses is used for symmetry; and $H$ is closed under products is used for transitivity.
Now, since $\equiv_H$ is an equivalence relation on $G$, by the Fundamental Theorem of Equivalence Relations, $\equiv_H$ induces a partition on $G$; that is, $G$ is broken up into disjoint parts, one for each equivalence class. Our next goal is to figure out if we have some description of the equivalence classes that is independent of the equivalence relation (this is very useful in general). Indeed, we do:
Theorem. Let $G$ be a group and let $H$ be a subgroup; let $x\in G$. The equivalence class of $x$ under the relation  $\equiv_H$ is equal to the set $Hx = \{hx\mid h\in H\}$. That is,
$$[x]_H = \{y\in G\mid x\equiv_Hy\} = \{hx\mid h\in H\} = Hx.$$
Proof. We need to show that each element in $Hx$ is in $[x]_H$, and that each element in $[x]_H$ is in $Hx$.
Let $z\in Hx$; that means that $z = hx$ for some $h\in H$. Then
$$xz^{-1} = x(hx)^{-1} = x(x^{-1}h^{-1}) = h^{-1}\in H,$$
so by definition we have that $x\equiv_H z$. Thus, if $z\in Hx$, then $z\in[x]_H$. So $Hx\subseteq[x]_H$.
Conversely, let $y\in [x]_H$. Then $x\equiv_H y$, so $xy^{-1}\in H$. Thus, there exists $h\in H$ such that $xy^{-1}=h$. Multiplying on the right by $y$ we get $x=hy$, and multiplying on the left by $h^{-1}$ we get $h^{-1}x = y$. Since $h^{-1}\in H$, we get $y = h^{-1}x \in Hx$. Thus, if $y\in[x]_H$ then $y\in Hx$, so $[x]_H\subseteq Hx$.
Putting the two inclusions together, we conclude that $[x]_H = Hx$ for each $x\in G$. QED
Corollary. Let $G$ be a group, $H$ a subgroup. Then:

*

*$Hx$ is nonempty for each $x\in G$.

*$\displaystyle G = \mathop{\cup}_{x\in G} Hx$.

*For all $x,y\in G$, if $Hx\cap Hy\neq\emptyset$, then $Hx=Hy$.

Proof. This follows from the fact that since the sets of the form $Hx$ are exactly the equivalence classes of the equivalence relation $\equiv_H$, they form a partition of $G$. QED
Corollary. Let $G$ be a group, $H$ a subgroup. For all $x,y\in G$, $x\equiv_H y$ if and only if $Hx = Hy$.
We give the sets of the form $Hx$ a name:
Definition. Let $G$ be a group, $H$ a subgroup, and $x\in G$. The set
$$Hx = \{ hx\mid h\in H\}$$
is called the right coset of $x$ modulo $H$.
"Coset" is short for "congruence set", because the right coset is exactly the set of all things that are congruent on the right to $x$ modulo $H$.
In general, when you have an equivalence relation, the equivalence classes can have different sizes. But not so with these equivalence relation: because they are obtained by taking all possible products with elements of $H$, all equivalence classes are bijectable.
Theorem. Let $G$ be a group and $H$ a subgroup. Let $x,y\in G$ be any two elements. Then there is a bijection between the sets $Hx$ and $Hy$, given by
\begin{align*}
\psi\colon Hx &\to Hy\\
hx&\mapsto hy
\end{align*}
Proof. To show that $\psi$ is one-to-one, let $hx,h'x\in Hx$ be such that $\psi(hx)=\psi(h'x)$. Then $hy = h'y$. Multiplying on the right by $y^{-1}$, we get $h=h'$, so $hx=h'x$. Thus, $\psi$ is one-to-one.
To show $\psi$ is onto, let $hy\in H$. Then $hx\in Hx$, and $\psi(hx)=hy$. Thus, $\psi$ is one-to-one and onto, so it is a bijection. QED
Now, let's assume that $G$ is finite, and $H$ is a subgroup. Then the equivalence relation $\equiv_H$ partitions $G$ into equivalence classes; each equivalence class is of the form $Hx$ for some $x\in G$, and by the previous theorem, they are all bijectable with one another, so they all have the same size, $k$. If there are $m$ distinct equivalence classes, each of size $k$, and they partition $G$, then the size of $G$ is the sum of the sizes of the distinct equivalence classes; that is, $|G|=mk$.
But what is $k$? $k$ is the size of the equivalence classes; they are all the same size. In particular, the equivalence class $He$ has size $k$. But what is $He$? Well,
$$He = \{ he\mid h\in H\} = \{h\mid h\in H\} = H.$$
That is, $He = H$, so that $H$ itself has size $k$.
Since $|G|=mk = m|H|$, that means that $|H|$ divides $|G|$. That is:
Corollary [Lagrange's Theorem]. If $G$ is a finite group, and $H$ is a subgroup, then the size of $H$ divides the size of $G$.
You might ask if you can define a "congruence on the left"; yes, you can. We say $x$ and $y$ are congruent on the left modulo $H$ if $x^{-1}y\in H$, and we write $x{}_H\equiv y$. If we proceed as above, then we get that the equivalence class of $x$ modulo $H$ on the left is $xH$ (instead of $Hx$); the process is completely analogous; these are called left cosets of $H$. Turns out that there is a bijection between left and right cosets. One is tempted to define the bijection by sending the coset $xH$ to the coset $Hx$, but it turns out that this is not well defined (you can have $xH = yH$, but also have $Hx\neq Hy$). However, mapping $xH$ to the coset $Hx^{-1}$ works out (I'll leave it to you to work it out), so that the number of left cosets and the number of right cosets of $H$ in $G$ are the same, and the size of any left coset is the same as the size of any right coset of $H$. In general, the equivalence relation "congruent on the left modulo $H$" is not the same as the equivalence relation "congruent on the right modulo $H$"; the case when they are the same is interesting in its own right, and corresponds to the case when $H$ is a normal subgroup, which has a lot of important consequences all of its own that you will no doubt discover soon.

A: I cannot yet write comments, so I'll write an answer.
Have you tried reading:
http://en.wikipedia.org/wiki/Lagrange%27s_theorem_(group_theory)
Maybe what you find confusing is that left cosets are not subgroups, just subsets of the group. You don't give many clues about your actual concerns...


text:
Q: Castle Windsor 3.0 Different services with same names -- how? Suppose, I have two interfaces IFirst and ISecond, both with several implementations, e.g. FirstClassForMe, FirstClassForYou, SecondClassForMe, SecondClassForYou.
I want to register them in IoC container (no matter which lifestyle):
this.container.Register(
    Component.For<IFirst>().ImplementedBy<FirstClassForMe>().Named("Me"),
    Component.For<IFirst>().ImplementedBy<FirstClassForYou().Named("You"),
    Component.For<ISecond>().ImplementedBy<SecondClassForMe>).Named("Me"),
    Component.For<ISecond>().ImplementedBy<SecondClassForYou>().Named("You"))

I want to use this as follows:
var forWho = this.GetCode();
var first = this.Container.Resolve<IFirst>(forWho);
var second = this.Container.Resolve<ISecond>(forWho);
this.Work(first, second);

But in windsor, I get an ComponentRegistrationException

Component Me could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.

However, I believe, it is possible to resolve this dependency, as far as pairs (interface; code) are unique, for each registration. Is it possible to make windsor work according to this scenario? E.g. to find all registrations for IFirst, and then select one by name.

A: Windsor's Service Overrides would work for what you'd like to do.

redpajama_set_name: RedPajamaStackExchange


text:
Q: retrieving standard fields in metadata request On retrieving metadata for sobjects, including standard ones i.e Account object, I note that I am passed back only the custom fields for this object. Any suggestions on how I include standard fields in my retrieve request, so that when I interrogate the results I get the complete picture of all fields, both standard and custom ?

A: The Metadata API does not support a number of fields, specifically mentioning:

Standard fields that aren't customizable, such as autonumber fields or system fields

This means that, for example, you can't retrieve Account.Name, but you could retrieve Lead.LeadSource (because it is customizable).
If you want to get a full list of fields, you need to use either the SOAP or REST API's describeSObject/describeSObjects call. Take a look at the documentation for either API for more details.


text:
Q: PermissionError occurred when tried to access '/usr/local/Cellar/tesseract/4.1.1/share/tessdata/' I'm learning how to use tesseract, and I have just installed tesseract using homebrew and pytesseract using pip.
My code looks like this:
pytesseract.pytesseract.tesseract_cmd = "/usr/local/Cellar/tesseract/4.1.1/share/tessdata/"

#...

But when I ran it, I got this error:
PermissionError: [Errno 13] Permission denied: '/usr/local/Cellar/tesseract/4.1.1/share/tessdata/'

I'll provide further info if you need.

A: This worked for me
try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract

pytesseract.pytesseract.tesseract_cmd = "/usr/local/bin/tesseract"

print(pytesseract.image_to_string(Image.open("./test.jpg")))

I have installed tesseract with brew install tesseract and pytesseract in a new virtualenv with pip install pytesseract. My permission to the tesseract executable (ls -la $(which tesseract) are
lrwxr-xr-x  1 p13rr0m  admin  39 May 26  2020 /usr/local/bin/tesseract -> ../Cellar/tesseract/4.1.1/bin/tesseract

A: This is probably occurs because tessdata is not executable. In the README they say as follows:
import pytesseract

# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'
# Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'

The variable tesseract_cmd is used as follows in this file under the function run_tesseract:
    cmd_args = []
...
    cmd_args += (tesseract_cmd, input_filename, output_filename_base)
...
    try:
        proc = subprocess.Popen(cmd_args, **subprocess_args())
    except OSError as e:
        if e.errno != ENOENT:
            raise e
        raise TesseractNotFoundError()

The exception is probably raised from the try-except block, because you cannot execute an unexecutable file, resulting in a permission error.
What you should do is to find the tesseract executable and refer to it instead of tessdata. As pointed out by @p13rr0m in his answer , it is probably located in "/usr/local/bin/tesseract". In such a case you should not modify the variable tesseract_cmd as it is initially referring to the command tesseract which is already accessible from your PATH environment variable.

A: I solved this by doing these:

*

*Install tesseract by homebrew like this: brew install tesseract

*Create a new venv: python -m venv yourVenvName

*Inside the venv, run pip install pytesseract
You don't need to use tesseract_cmd, if you are using mac.
And try if you can use tesseract inside the venv.


text:
Q: MySQL datetime vs TIMESTAMP with time zones OK I have a MySQL DB in UTC timezone, I don't want to change that (it is a AWS RDS). I am running all queries through php_mysqli I am using the following after connection to set timezone:
SET time_zone = "-05:00"

I have a table test with 2 fields:
date_add => DATETIME
date_upd => TIMESTAMP
The MySQL NOW() and CURRENT_TIMESTAMP match and are in right timezone. Confirmed my running:
SELECT NOW()
SELECT CURRENT_TIMESTAMP

When I run the following:
INSERT INTO `test` SET `date_add`=NOW()

then
SELECT * FROM `test`

I get matching date_add and date_upd with correct time zone
However when I look at the raw table in CLI or phpMyAdmin the results are different, like in different timezones?
+---------------------+---------------------+
| date_add            | date_upd            |
+---------------------+---------------------+
| 2013-06-07 15:57:09 | 2013-06-07 20:57:09 |
+---------------------+---------------------+

Not sure if the 2 fields are just set to differnt time zones are what is going on any help with this would be greatly appreciated... thx

A: That is because datetime does not have a timezone, whereas timestamp have timezone.
http://dev.mysql.com/doc/refman/5.0/en/datetime.html

A: my guess would be that set timezone just sets the local environment variable and has no affect on what is actually saved. it just affects how it is viewed when queried.
in phpmyadmin you dont do the same set first, so you see it with default timezone.

A: In MySQL, timestamp in fact is always in UTC, i.e., when you insert a timestamp at your local time zone to db, it's automatically converted to UTC on the database server. So it's consistent everywhere. I'd recommend that you always use timestamp if there are clients in different time zones. Also timestamp is more efficient than datetime.


text:
Q: Are the recently observed Dirac monopoles separable? I just went through Observation of Dirac monopoles in a synthetic magnetic field.
What exactly has been observed?
More importantly, are these monopoles localized inside the apparatus (no stray monopole field lines coming out), or can they be used to create tangible monopoles? (By tangible monopoles I mean an object that is overall a monopole without any external influence. It may contain a condensate or similar inside)

A: After reading this paper, I wracked my brain trying to come up with the perfect analogy. Suffice it to say I failed, so here is my less than ideal answer.
The monopole created and referred to in this article is not a true Dirac monopole. It is no more a real monopole than a thermal vacuum testing chamber is outer space. That is, it is an artificially created object that exhibits most of the desirable properties of a Dirac monopole, specifically the properties that many scientists really want to experiment on. Although I am not a particle physicist and don't work much with theories involving monopoles, it came across to me like the monopole was localized; there was no net flux of magnetic field into or out of the laboratory. Instead, they often refer to it being monopolar within the scope of a derived synthetic magnetic field, not a true magnetic field as jinawee pointed out in the comments.
That said, this is still a major breakthrough. This represents that scientists have the ability to create something in a lab that, when used in certain experiments, would behave just like we expect a real Dirac monopole would.

Edit:
I should probably have pointed out that they only describe producing one type of pole at a time (specifically North poles I believe), which is why if they were true monopoles, there would be a net flux of magnetic field into/out of the laboratory.

A: Let me make quite clear that the recent experiment does NOT imply the detection of a true magnetic monopole. Somehow, in all the excitement, the word "synthetic" was dropped rather quickly from the phrase "synthetic magnetic field".
A synthetic magnetic field is a physical quantity that obeys the same equations as a magnetic field, typically realized in things like the velocity field of the atoms inside a BEC. The recent paper claims the observation of the analogue of a Dirac monopole in such a quantity, and it is a significant result in the field of quantum simulation. However, their experiment is made completely out of atoms, and therefore of protons, neutrons and electrons. It cannot have any magnetic flux into or out of any region within or around it, and it does not violate the laws of electromagnetism. Indeed, it's built within them.
Synthetic magnetic fields are explained nicely in this review:

Colloquium: Artificial gauge potentials for neutral atoms. Jean Dalibard et al. Rev. Mod. Phys. 83 no. 4, 1523–1543 (2011). arXiv:1008.5378.

They describe a simple toy model which captures, I think the basics of the recent experiment.

Consider a two-level atom which is at the influence of an external field which couples its two internal states. Its hamiltonian can be written as
$$
H=\left(\frac{P^2}{2m}+V\right)+U,
$$
where the part in brackets does not couple to the internal state, and
$$
U=\frac{\hbar\Omega}{2}\begin{pmatrix}\cos\theta&e^{-i\phi}\sin\theta \\ e^{i\phi}\sin\theta & -\cos\theta\end{pmatrix}
$$
in the ground - excited state basis $\{|g\rangle,|e\rangle\}$. In such a scheme $\Omega$ is the Rabi frequency and determines the strength of the coupling;  $\phi$ is the phase of the laser that's used to couple the states; and $\theta$ is called the mixing angle and determines whether the coupling acts more like a Stark shift (at $\theta=0$), more like a pure coupling (at $\theta=\pi/2$), or somewhere in between. The distinction between those regimes is dependent on the detuning to the atomic transition, and it can vary with the atom's position $\mathbf{r}$.
The game here is to have the atom move around slowly enough that it will always stay in the ground state of the laser-induced atomic hamiltonian $U$. This is the first of the two eigenstates
$$
|\chi_1\rangle
=\begin{pmatrix}\cos(\theta/2) \\ e^{i\phi}\sin(\theta/2)\end{pmatrix},
\quad
|\chi_2\rangle
=\begin{pmatrix}-e^{-i\phi}\sin(\theta/2)\\ \cos(\theta/2)\end{pmatrix},
$$
which depend on the position $\mathbf{r}$ through the laser parameters $\theta$ and $\phi$. If you vary these parameters slowly enough, you will stay in the same eigenstate as you started in, without any nonadiabatic transitions.
More precisely, because the states $|\chi_j\rangle$ are a basis, one can always write the atom's wavefunction as
$$
|\Psi(\mathbf{r},t)\rangle=\langle \mathbf{r}|\Psi(t)\rangle
=
\sum_j\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle.
$$
(Note that this is the position-dependent internal state, which can be obtained from the full state $|\Psi(t)\rangle$ by projecting on a position state $|\mathbf{r}\rangle$.) If the atom's velocity spread is small enough, it will never transition to $|\chi_2\rangle$ and one can describe the system simply in terms of a single Schrödinger equation for $\psi_1(\mathbf{r},t)$.
To get that equation, you first have to work rigorously with the full state, and then afterwards neglect the possibility of transitions. Thus, if you act with the momentum $\mathbf{P}=-i\hbar\nabla$ on the component $\psi_j(\mathbf{r},t) |\chi_j(\mathbf{r})\rangle$, you will get contributions from both factors:
$$
\nabla\left[\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle\right]
=\left(\nabla\psi_j(\mathbf{r},t)\right)|\chi_j(\mathbf{r})\rangle
+\psi_j(\mathbf{r},t)\nabla_\mathbf{r}|\chi_j(\mathbf{r})\rangle.
$$
Multiplying on the left with the completeness relation $\sum_i|\chi_i\rangle\langle\chi_i|$, we can obtain a nice expression for the action of the momentum:
$$
\mathbf{P}\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle
=\sum_i|\chi_i\rangle
\left[\delta_{ij}\mathbf{P}-\mathbf{A}_{ij}\right]
\psi_j(\mathbf{r},t),
$$
where $\mathbf{A}_{ij}=i\hbar\langle\chi_i|\nabla_\mathbf{r}|\chi_j\rangle$ is, broadly speaking, the rate at which nonadiabatic transitions can occur. Dotting this again with the momentum operator, one obtains
$$
P^2\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle
=\sum_{l,i}|\chi_l\rangle(\delta_{li}\mathbf{P}-\mathbf{A}_{li})
(\delta_{ij}\mathbf{P}-\mathbf{A}_{ij})\psi_j(\mathbf{r},t),
$$
as long as one can neglect a term in $\nabla\cdot\mathbf{A}_{ij}=i\hbar\nabla\cdot\langle\chi_i|\nabla_\mathbf{r}\chi_j\rangle$. This corresponds to saying that the potential's variation is only relevant to first order at the low momenta encompassed by $\Psi$.
One can then neglect the possibility of transitions, and simply ignore all the terms that have $|\chi_2\rangle$ in them. (Or one might not, in which case you can try and build non-Abelian gauge fields instead.) If you do this, all the sums go away, and you get the simple Schrödinger equation
$$
i\hbar\frac{\partial\psi_1}{\partial t}
=
\left[
\frac{1}{2m}(\mathbf{P}-\mathbf{A})^2+V+\frac{\hbar\Omega}{2}+W.
\right]\psi_1
$$

This equation is identical in form to that of a single particle under the action of the old potential $V$, an 'electrostatic potential'
$$W=\frac{\hbar^2}{2m}|\langle\chi_2|\nabla\chi_1\rangle|^2$$
which measures virtual transitions from $|\chi_1\rangle$ to $|\chi_2\rangle$ and back, and a magnetic field with vector potential
$$\mathbf{A}=i\hbar\langle\chi_1|\nabla_\mathbf{r}|\chi_1\rangle.$$
This magnetic field will be nonzero whenever $\theta$ and $\phi$ both have significant spatial dependence with non-collinear gradients.
Most importantly, this 'magnetic field' depends on experimentally controllable parameters through $\theta(\mathbf{r})$ and $\phi(\mathbf{r})$. If one can build a sufficiently clever experiment, the 'field' $\mathbf{B}$, which is really the vector field
$$\nabla\times\langle\chi_1|\nabla\chi_1\rangle,$$
can exhibit monopolar behaviour. One can create 'coupled' monopoles (i.e. separated by a finite Dirac string) or even take one of those out of the cloud to make a 'true' Dirac monopole as far as the cloud is concerned. It is my understanding that this is the case for the recent experiment. This does not, of course, imply that any net real magnetic flux is coming out of that apparatus.

A: It is not a monopole, is just an artifact. Note that any addition of dipolar contributions of magnetic field (spin, coils, magnets…) must be dipolar or of a higher order magnetic field, in no case it could be monopolar. It is to say, there is not possible to construct a monopolar field as a superposition of dipolar (or higher order) contributions. The artifact the authors claim as a Dirac monopole is not that. It is simply a collection of atomic spin that invert the direction when the external field rotates. Intimately joined with every spin magnet there are the magnetic closed field lines that the author did not draw.
Is perhaps the pression to publish papers under this kind of papers?


text:
Q: How to solve a problem with bind_param on a non-object? I use bind_param() member function in my query, but I got error with my code.
This is the piece of my code:
<?php

session_start();
include_once 'functions.php';
loging(basename(__FILE__));
if (!isset($_SESSION['user'])) {
    redirect('login.php');
}

$day_id = date('w');

$database = new mysqli('127.0.0.1', 'user', 'user', 'kantin');
$sesi = $_POST['sesi'];
$lauk = $_POST['lauk'];
$sayur = $_POST['sayur'];
$minuman = $_POST['minuman'];
$user = $_SESSION['username'];

$query_user = "SELECT * FROM user WHERE username LIKE '" . $user . "'";
$statement_user = $database->query($query_user);
$row_user = $statement_user->fetch_assoc();
$id_user = $row_user['user_id'];

$query_sesi = "SELECT * FROM sesi WHERE sesi LIKE '" . $sesi . "'";
$statement_sesi = $database->query($query_sesi);
$row_sesi = $statement_sesi->fetch_assoc();
$id_sesi = $row_sesi['sesi_id'];

$query_alt_id = "SELECT * FROM alternatif WHERE id_hari='" . $day_id . "' AND id_sesi= '" . $id_sesi . "' AND lauk_alt LIKE '" . $lauk . "'";
$statement_alt_id = $database->query($query_alt_id);
while ($row_alt_id = $statement_alt_id->fetch_assoc()) {
    $id_alt = $row_alt_id['alternatif_id'];
    $id_menu = $row_alt_id['lauk_alt'];
    $id_hari = $row_alt_id['id_hari'];
    $id_sesi = $row_alt_id['id_sesi'];
}

$query_insert = "INSERT INTO update (`id_menu_alt`, `id_user`, `id_hari`, `id_sesi`) VALUES (?,?,?,?)";
$statement_insert = $database->prepare($query_insert);
$statement_insert->bind_param('iiii', $id_alt, $id_user, $id_hari, $id_sesi);
$statement_insert->execute();

redirect('today_menu.php');
?>

When I execute the code, I get the error:

Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\IBAD\Kantin_Pakoper\change_alternatif_process.php on line 40

A: You're getting an error from the call to prepare(), so it's returning false instead of a mysqli_stmt. To see the MySQL error message, do:
$statement_insert = $database->prepare($query_insert) or die($database->error);

In this case, the problem is that update is a MySQL reserved word. To use it as a table name, you need to put it in backticks:
$query_insert = "INSERT INTO `update` (`id_menu_alt`, `id_user`, `id_hari`, `id_sesi`) VALUES (?,?,?,?)";

I find it strange that you put all the column names in backticks, even though they don't need it, but you didn't put the table name in backticks.
Also, why aren't you using prepared statements for all the other queries? If you don't use bind_param(), you need to escape the strings before concatenating them into the queries.

A: Your query has not been prepared properly, probably because the syntax is incorrect. In future use an if statement in your prepare in order that you can avoid other operations if the syntax is wrong, as follows;
if($statement_insert = $database->prepare($query_insert)) {
   $statement_insert->bind_param('iiii', $id_alt, $id_user, $id_hari, $id_sesi);
   $statement_insert->execute();
}
elseif($database->error) {
   echo "Could not prepare SQL: " . $database->error;
}

The problem with your current SQL is that update is a special word in MySQL (and SQL in general), so you need to put the table name in the correct markup
$query_insert = "INSERT INTO `update` (`id_menu_alt`, `id_user`, `id_hari`, `id_sesi`) VALUES (?,?,?,?)";


text:
Q: I think i have have a bug in JSON.Net So I'm a bit of a beginner think i've got some unexpected behaviour/ a bug, though it may well be operator error rather than anything else but either way I'm stumped and don't know what to do.
I'm reading in a JSON string! from
https://beta-api.betfair.com/exchange/betting/rest/v1/en/navigation/lhm.json
I'm passing it with JSON.Net(v6.0.3 from Nuget) ill get to how in minute, but im getting a error where two of the supposedly unique objects returned have the same ID, something of a problem. While trying to work out where I had mashed it up I looked at the JSON string with the Visual Studio JSON Visualiser and that is showing two different ID's as expected.
Edit
I've uploaded two pictures but had to od it externally and copied in the section of JSON that's relevant.
http://imgur.com/pk2hIJI,SZDSSLh
{
                                "children": [
                                    {
                                        "children": [
                                            {
                                                "exchangeId": "1",
                                                "id": "1.114548892",
                                                "name": "Moneyline",
                                                "type": "MARKET"
                                            }
                                        ],
                                        "id": "27229997",
                                        "name": "Hamilton @ Calgary",
                                        "type": "EVENT"
                                    },
                                    {
                                        "children": [
                                            {
                                                "exchangeId": "1",
                                                "id": "1.114548889",
                                                "name": "Moneyline",
                                                "type": "MARKET"
                                            }
                                        ],
                                        "id": "27229996",
                                        "name": "Toronto @ Ottawa",
                                        "type": "EVENT"
                                    }
                                ],
                                "id": "74587734296",
                                "name": "Games 18 July",
                                "type": "GROUP"
                            },

To fetch the string i am using an object inherited from HTTPclient, with
        BFresponce = Await Me.GetAsync(BetFairBetaAddress & RestAddress & Method)
        Dim x = Await BFresponce.Content.ReadAsStringAsync 'not normaly here just so i can veiw the string
        Return JsonConvertHelper.DeserializeObject(Of T)(Await BFresponce.Content.ReadAsStreamAsync())

With my own help function
   Public Shared Function DeserializeObject(Of T)(stream As Stream) As T
        Dim serializer As New JsonSerializer()
        Using streamReader As New StreamReader(stream)
            Return serializer.Deserialize(streamReader, GetType(T))
        End Using
    End Function

And the class beeing passed in T is
Namespace BetFairNS
Public Class NavigationData
    Public Property name As String
    Public Property id As Single
    Public Property exchangeId As Integer
    Public Property type As NavigationDataType
    Public Property children As List(Of NavigationData)
End Class
Public Enum NavigationDataType
    EVENT_TYPE
    GROUP
    [EVENT]
    MARKET
    RACE
End Enum

End Namespace
So the crux of it is have i mashed this up somewhere? or if its a bug what do I do?

A: There is nothing wrong with Json.Net.  The JSON data file you linked to has 260 instances of recurring IDs, all of them in the Horse Racing category.  Here are the first 5:
Duplicate id found: 1.114591860
Path 1: ROOT > Horse Racing > 1600m 3yo > 1600m 3yo
Path 2: ROOT > Horse Racing > FRA > Chant (FRA) 14th Jul > 1600m 3yo

Duplicate id found: 1.114591859
Path 1: ROOT > Horse Racing > 1600m 3yo > To Be Placed
Path 2: ROOT > Horse Racing > FRA > Chant (FRA) 14th Jul > To Be Placed

Duplicate id found: 1.114591864
Path 1: ROOT > Horse Racing > 1600m 3yo > 1600m 3yo
Path 2: ROOT > Horse Racing > FRA > Chant (FRA) 14th Jul > 1600m 3yo

Duplicate id found: 1.114591863
Path 1: ROOT > Horse Racing > 1600m 3yo > To Be Placed
Path 2: ROOT > Horse Racing > FRA > Chant (FRA) 14th Jul > To Be Placed

Duplicate id found: 1.114591869
Path 1: ROOT > Horse Racing > 1600m Grp1 > 1600m Grp1
Path 2: ROOT > Horse Racing > FRA > Chant (FRA) 14th Jul > 1600m Grp1

You can check this simply by downloading the file using a web browser, saving it to disk, then opening it with a text editor and searching for the ID values I've listed.  Each one appears twice, at different places in the hierarchy.
Does it say somewhere in the API documentation for this site that all IDs in the JSON will be distinct?  It looks to me like they simply decided to list the same node at more than one level for browsing convenience (i.e. list all the races directly under "horse racing" and also list them by country/event).  You are probably going to need to change your assumptions about the data and adjust your code accordingly.
EDIT
Now that you have shared the actual ID / name of the node that is giving you trouble, the problem is clear.  You've declared the id field of your NavigationData class as Single when it should be String.  Single is a floating point type, and is not suitable for holding ID values, even if they may have a decimal point in them.
Again, take a closer look at the actual JSON file.  If you search for "Hamilton @ Calgary", you will see that it has an ID of 27229997.  The other node, "Toronto @ Ottawa", immediately beneath it, has an ID of 27229996.  In your debugger image, the values both show as 27229996.0  The IDs are getting mangled most likely because Single does not have the capability to represent the number 27229997 exactly as a binary floating point number, so the closest neighboring value is being chosen instead.  This is a very bad thing when you need an exact representation (as you always do with an ID).
The key point is to use the right tool for the job.  You cannot assume that a third-party ID will always be numeric or contain only a single decimal point, and you will never do math operations on an ID.  In short, there's no reason to make it a decimal type.  Declare it as String and that will fix the problem.  I would also recommend the same for the exchangeId field for the same reason.


text:
Q: Why is [x, 5-2x] not a vector subspace of R^2? For my homework there is a problem asking to show if [x, 5-2x] is or is not a vector subspace of R^2. I am having a lot of trouble understanding why this specific set is not a subset of R^2 as it seems to follow both scalar and addition rules the same way as any other R^2 subset would.
a([x, 5-2x]) + b([y, 5-2y])
= [ax, a5-a2x] + [by, b5-b2y]
= [ax + by, (a5-a2x) + (b5-b2y)] which seems to be a subset of R^2?
Am I misunderstanding how to tell if the set is a subset or not?
I know that it is not a subset due to the answer on the back of the book telling me that it is not.

A: Well, this set $S = \{[x,5-2x]; x \in \mathbb{R}\}$ is not closed under multiplication by a scalar. The vector $[1,3]$ is in $S$ but $[2,6]$ is not, as clearly $6 \not = 5-2×2$.
In particular, you made mistakes in your arithmetic verifying that $S$ is closed under addition. Let $X=[x,5-2x]$ and $Y=[y,5-2y]$ be any $2$ elements in $S$. Then for $S$ to be closed under addition, the sum $X+Y =$ $[x+y, (5-2x) + (5-2y)]$ $=[(x+y), 10-2(x+y)]$ must be in $S$ for any such $X$ and $Y$, which would imply that $10-2(x+y)$ must equal $5-(x+y)$ for any $x \in \mathbb{R}$ and $y \in \mathbb{R}$. But what about say $X =[3,-1]$ i.e., $x=3$ and $Y=[4,-3]$ i.e., $y=4$.


text:
Q: What is the order of integration of AR + MA Consider the following bivariate DGP for ($y_t,z_t$):
$y_t = \gamma(z_{t-1} + \theta_{21}\epsilon_{2,t-1} + u_{2,t}) + \theta_{11} \epsilon_{1,t-1} + u_{1,t} $
$z_t = z_{t-1} + \theta_{21}\epsilon_{2,t-1} + u_{2,t} $
With constraint
(i) $ 0 < \theta_{11} < 1$;
(ii) $\theta_{21} \neq 0$
The question is to discuss the I(d) of the processes and cointegration and if there exists a cointegration vector.
If we start with
$z_t = z_{t-1} + \theta_{21}\epsilon_{2,t-1} + u_{2,t} $
One can see that we have here a AR process with a unit root $\phi = 1$ and hence I(1) for that part.
Then we still have an MA part from which we know that a finite sum of random variables is covariance stationary and hence I(0) with the conclusion that $z_t$ = I(1) and $\Delta z_t$ = I(0).
If we move on to
$y_t = \gamma(z_{t-1} + \theta_{21}\epsilon_{2,t-1} + u_{2,t}) + \theta_{11} \epsilon_{1,t-1} + u_{1,t} $
We have $z_t$ in the equation so we have that $y_t$ is at least I(2) and if we follow my line of thought regarding that the MA part is still stationary and hence I(0) we conclude that $y_t$ = I(2) and $\Delta y_t$ = I(1).
If we change the situation and assume the following constraint
(i) $ \theta_{11} = 1$;
The MA part in $y_t$ becomes non stationary hence I(1) and then the $\Delta y_t$ becomes I(3); however I am not sure about this part.
Furthermore we conclude that $y_t$ and $z_t$ are cointegrated through the vector $[1, -\theta_{11}]'$.
I am really curious to see if my analysis is correct; thank you very much in advance. If there is any reference; kindly refer.


text:
Q: Sorting Server Side with AJAX, headers not working properly I've got a problem:
Not all headers work to sort the table, and some of them partially work, I.E.: Marca and Modelo work perfectly but idTipoDeVehiculo just works once and idAuto and FechaDeLanzamiento never work.
Okay, this is my index.php:
index.php
And this is the order-column.php:
order-column.php
Here is the AJAX, but I don't think the problem lies in there:
function orderColumn(column_name, column_order) {
  $.ajax({
    url: "order-column.php",
    data: 'orderby=' + column_name + '&order=' + column_order,
    type: "POST",
    success: function(data) {
      $('#demo-order-list').html(data);
    }
  });
}

I'm not allowed to use any plugins and forced to use AJAX.
Anyways, I tried everything and I'm completely lost, I hope someone can help me.

A: The problem is, that you did not declared your variables. See this:
if($orderBy == "idAuto" and $order == "desc") {
    $idAutoNextOrder = "asc";
}

If the $orderBy not idAuto or $order is not desc, your $idAutoNextOrder won't created but later you reference to it.
$idAutoNextOrder = "desc"; //<----Init here
if($orderBy == "idAuto" and $order == "desc") {
    //change if need
    $idAutoNextOrder = "asc";
}


text:
Q: Как обратится к элементу из списка v-for Как сделать проверку , что если допустим нажал на в первом блоке на слово "Посмотреть" , чтобы у меня отображались одобрить и отказать только для первого блока , а не для всех ?

new Vue({
   el: '#app',
   data() {
     return {
      requestnames: [{},{},{},{}],
      qwers: [],
      requesT: undefined,
      requesTT: undefined,
     }
   }
 });
.secon {
   background: rgba(0, 0, 0, 0.45);
   box-shadow: 0vh 0.6006vh 4.804vh 0.4504vh rgba(0, 0, 0, 0.25);
   border-radius: 3.003vh;
   width: 55.3vw;
   height: 75.3103vh;
}

.head-request {
   height: 8.610vh;
   background: linear-gradient(rgba(41, 146, 254, 0.65));
   box-shadow: 0vh 0.6006vh 4.804vh 0.45vh rgba(0, 0, 0, 0.25);
   border-radius: 3.003vh 3.003vh 0vh 0vh;
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 3.405vh;
   line-height: 6.756vh;
   letter-spacing: -0.04em;
   color: #FFFFFF;
   text-shadow: 0vh 0.4504vh 0.75vh rgba(0, 0, 0, 0.4);
   display: flex;
   align-items: center;
   padding-left: 3.003vh;
}

.main-request {
   margin: 2.38vh;
}

.mainrequesters {
   display: flex;
   flex-wrap: wrap;
}

.name-player {
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.38vh;
   line-height: 110%;
   display: flex;
   align-items: center;
   letter-spacing: -0.06em;
   color: #FFFFFF;
   padding-bottom: 0.7462vh;
   padding-left: 0.7462vh;
}

.zapros-player {
   height: 13.223vh;
   width: 30.128vh;
   background: linear-gradient(rgba(255, 255, 255, 0.3));
   box-shadow: 0vh 0.6611vh 0.6611vh rgba(0, 0, 0, 0.5);
   border-radius: 1.49vh;
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.089vh;
   line-height: 2.89vh;
   display: flex;
   align-items: center;
   letter-spacing: -0.06em;
   color: #FFFFFF;
   display: flex;
   justify-content: left;
   padding-left: 0.7462vh;
}

.name-admin {
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.38vh;
   line-height: 110%;
   display: flex;
   justify-content: right;
   letter-spacing: -0.06em;
   color: blue;
   padding-top: 2.238vh;
   padding-bottom: 0.7462vh;
}

.accept {
   height: 5.223vh;
   width: 34.328vh;
   background: linear-gradient(rgba(255, 255, 255, 0.3));
   box-shadow: 0vh 0.6611vh 0.6611vh  rgba(0, 0, 0, 0.5);
   border-radius: 1.49vh;
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.089vh;
   line-height: 110%;
   display: flex;
   float: right;
   color: lightgreen;
   justify-content: right;
   align-items: center;
   padding-right: 0.7462vh;
}

.refusal {
   height: 5.223vh;
   width: 34.328vh;
   background: linear-gradient(rgba(255, 255, 255, 0.3));
   box-shadow: 0vh 0.6611vh 0.6611vh  rgba(0, 0, 0, 0.5);
   border-radius: 1.49vh;
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.089vh;
   line-height: 110%;
   display: flex;
   float: right;
   color: red;
   justify-content: right;
   align-items: center;
   padding-right: 0.7462vh;
}

.buttons {
   display: flex;
   justify-content: space-around;
}

.accept-request {
   height: 5vh;
   width: 12vw;
   background: lightgreen;
   border-radius: 1.49vh;
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.38vh;
   line-height: 110%;
   color: #FFFFFF;
   &:active {
      background: linear-gradient(rgba(144, 238, 144, 0.7));
   }
}

.refusal-reauet {
   height: 5vh;
   width: 12vw;
   background: red;
   border-radius: 1.49vh;
   font-family: 'Montserrat';
   font-style: normal;
   font-weight: 500;
   font-size: 2.38vh;
   line-height: 110%;
   color: #FFFFFF;
   &:active {
      background: linear-gradient(rgba(255, 0, 0, 0.7));
   }
}

                  Замена

Нове имя:

                        id

                        Статус

                     <button class="rozsmatret" v-on:click="requesTT =                         'reqq'">Посмотреть</button>
                     <button class="sxvaliti" v-if="requesTT ==                                  'reqq'">Одобрить</button>
                     <button class="otkaz" v-if="requesTT ==                                      'reqq'">Отказать</button>

A: Вот так, например. Просто записываете индекс и сверяете. Если надо скрывать - просто его можете затирать (тогда в methods функцию вынести можно).

new Vue({
  el: '#app',
  data() {
    return {
      requestnames: [{}, {}, {}, {}],
      qwers: [],
      requesT: undefined,
      requesTT: undefined,
      currentElement: null,
    }
  },
});
.secon {
  background: rgba(0, 0, 0, 0.45);
  box-shadow: 0vh 0.6006vh 4.804vh 0.4504vh rgba(0, 0, 0, 0.25);
  border-radius: 3.003vh;
  width: 55.3vw;
  height: 75.3103vh;
}

.head-request {
  height: 8.610vh;
  background: linear-gradient(rgba(41, 146, 254, 0.65));
  box-shadow: 0vh 0.6006vh 4.804vh 0.45vh rgba(0, 0, 0, 0.25);
  border-radius: 3.003vh 3.003vh 0vh 0vh;
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 3.405vh;
  line-height: 6.756vh;
  letter-spacing: -0.04em;
  color: #FFFFFF;
  text-shadow: 0vh 0.4504vh 0.75vh rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  padding-left: 3.003vh;
}

.main-request {
  margin: 2.38vh;
}

.mainrequesters {
  display: flex;
  flex-wrap: wrap;
}

.name-player {
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.38vh;
  line-height: 110%;
  display: flex;
  align-items: center;
  letter-spacing: -0.06em;
  color: #FFFFFF;
  padding-bottom: 0.7462vh;
  padding-left: 0.7462vh;
}

.zapros-player {
  height: 13.223vh;
  width: 30.128vh;
  background: linear-gradient(rgba(255, 255, 255, 0.3));
  box-shadow: 0vh 0.6611vh 0.6611vh rgba(0, 0, 0, 0.5);
  border-radius: 1.49vh;
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.089vh;
  line-height: 2.89vh;
  display: flex;
  align-items: center;
  letter-spacing: -0.06em;
  color: #FFFFFF;
  display: flex;
  justify-content: left;
  padding-left: 0.7462vh;
}

.name-admin {
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.38vh;
  line-height: 110%;
  display: flex;
  justify-content: right;
  letter-spacing: -0.06em;
  color: blue;
  padding-top: 2.238vh;
  padding-bottom: 0.7462vh;
}

.accept {
  height: 5.223vh;
  width: 34.328vh;
  background: linear-gradient(rgba(255, 255, 255, 0.3));
  box-shadow: 0vh 0.6611vh 0.6611vh rgba(0, 0, 0, 0.5);
  border-radius: 1.49vh;
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.089vh;
  line-height: 110%;
  display: flex;
  float: right;
  color: lightgreen;
  justify-content: right;
  align-items: center;
  padding-right: 0.7462vh;
}

.refusal {
  height: 5.223vh;
  width: 34.328vh;
  background: linear-gradient(rgba(255, 255, 255, 0.3));
  box-shadow: 0vh 0.6611vh 0.6611vh rgba(0, 0, 0, 0.5);
  border-radius: 1.49vh;
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.089vh;
  line-height: 110%;
  display: flex;
  float: right;
  color: red;
  justify-content: right;
  align-items: center;
  padding-right: 0.7462vh;
}

.buttons {
  display: flex;
  justify-content: space-around;
}

.accept-request {
  height: 5vh;
  width: 12vw;
  background: lightgreen;
  border-radius: 1.49vh;
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.38vh;
  line-height: 110%;
  color: #FFFFFF;
  &:active {
    background: linear-gradient(rgba(144, 238, 144, 0.7));
  }
}

.refusal-reauet {
  height: 5vh;
  width: 12vw;
  background: red;
  border-radius: 1.49vh;
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 500;
  font-size: 2.38vh;
  line-height: 110%;
  color: #FFFFFF;
  &:active {
    background: linear-gradient(rgba(255, 0, 0, 0.7));
  }
}

      Замена

Нове имя:
 id
 Статус

        <button class="rozsmatret" v-on:click="currentElement = i">Посмотреть</button>
        <button class="sxvaliti" v-if="currentElement === i">Одобрить</button>
        <button class="otkaz" v-if="currentElement === i">Отказать</button>


text:
Q: Как подсчитать с помощью конвейера команд количество блочных устройств ввода-вывода, доступных в системе? [Linux/Bash] Как подсчитать с помощью конвейера команд количество блочных устройств ввода-вывода, доступных в системе? Linux (bash)

A: если саму методику получения правильного списка блочных устройств оставить на совести преподавателя, задающего столь нетривиальные вопросы, и ограничиться, исключительно для илллюстрации, каким-нибудь банальным содержимым каталога /sys/block, то остаётся три достаточно неочевидные задачи:

*

*как получить список содержимого каталога исключительно средствами программы bash?

*как подсчитать количество строк (или слов) исключительно теми же средствами?

*куда? ну куда??? куда же здесь впихнуть ещё и конвейер?

ну что же, попробуем.

*

*тут достаточно просто, если принять во внимание, что echo является встроенной командой программы bash:
$ echo /sys/block/*

*тут возможно множество вариантов. наиболее простые, без использования циклов:

*

*поместить список в массив и вывести длину массива:
$ array=($(echo /sys/block/*)); echo ${#array[@]}

*или поместить список в массив аргументов с помощью (встроенной!) команды set и вывести его длину:
$ set /sys/block/*; echo $#

*впихивание конвейера - это, пожалуй, самая сложная часть. пока додумался только до такой перенагруженной конструкции с использованием (встроенной!) команды read:
$ echo /sys/block/* | ( read -a array; echo ${#array[@]} )

подумаю на досуге. может быть удастся упростить.


text:
Q: Question about Maven2 repositories mirroring I have set up a Maven 2 repository (call 'dev repository') using Apache Archiva which holds artifacts of my private projects.
If I build an artifact of my own project, say group1:cat for example, and Cat depends on { group1:dog, commons:collection }. The group1:cat and group1:dog are sit in dev repository, and commons:collection in the Central.
Now, when I build group1:cat, maven will fetch group1:dog and commons:collection, the problem is maven will always search in both dev repository and central repository to find the dependencies, but what I want is it search group1:dog in dev repositories only, and search commons:collection in central repositories only. I have central mirrors say central-mirror1 and central-mirror2, so how to configure maven so it will search commons:collection in default central repository and central-mirror-1,2 etc., and won't bother my dev repositories at all?

A: My setup uses my local Archiva instance to proxy central (and other 3rd party repositories).  In my super pom, I've changed my repositories to only point to my local Archiva, and not search central at all.  Everything comes in via my local proxy.
It's not quite what you're asking for, but I think it's an appropriate setup.
You can then use Archiva's black/white lists to tell it where to search for things.

A:
(...) what I want is it search group1:dog in dev repositories only, and search commons:collection in central repositories only.

I don't know how to achieve this and I don't think it's possible. How could maven be aware of the "source" repository for a given artifact?
But actually, why don't you make everything go through Archiva? What's the point of not using Archiva for all requests? If you don't want maven to check both repositories for your dependencies, it seems to be a pretty obvious solution. Moreover, people usually don't want to rely directly on central in a corporate environment (e.g. if it goes down you can't work anymore). No, really, I don't get it.
So, I'd just declare Archiva as a mirrorOf all repositories, like this:
<settings>
  ...
  <mirrors>
    <mirror>
      <id>internal-repository</id>
      <name>Maven Repository Manager running on repo.mycompany.com</name>
      <url>http://repo.mycompany.com/proxy</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
  </mirrors>
  ...
</settings>


text:
Q: "Can't visit this page" error when trying to access Google Scripts Google tech support are unable to help me because technically the problem is associated with a personal account.
I often write scripts which are linked to spreadsheets in Google Sheets for my clients. Usually, they make a copy of the spreadsheet on their own Google Drive when I am finished, and they can then continue to use the scripts I've written.
Recently I have 'transferred ownership' of a Google Sheet to a client. I am still able to edit the sheet and scripts file as a collaborator. However, when they try to access the scripts either by using the menu (Tools > Script Editor) or by navigating directly yo script.google.com, they get an unusual error message which reads...
Can't visit this page
It's not available for your account
Their Google account is a personal one, and it is only a week or two old.
Do I need to instruct them to enable scripts for Google Sheets somewhere? Or is there something I'm missing?

A: Found the problem.
My client had registered their account with their company's birth date instead of a real human's birth date. As such, they were under 13 years old which in the UK means Google restricted their account as if they were a child.


text:
Q: How to use each in Laravel as recurse? I have some objects like as:
array:8 [▼
  "_id" => MongoId {#261 ▶}
  "name" => "Objects"
  "default" => "900"
  "visibility" => "1"
  "type" => "2"
  "only_numbers" => null
  "value" => array:2 [▼
    0 => "59222778470e6c8e0b3c988a"
    1 => "59222880470e6cb90e3c9897"
  ]
  "available" => "1"
]

I try to display this on the page:
{{$field["name"]}} {{$field["value"]}}

But inside value exists keys on nested objects with the same structure.
So, I need to display these childrens.
How to do that using each operator in blade Laravel?
I tried:
@each('field.objects', $field["value"], 'nested')
Where template is:

    {{dd($v)}}
    @foreach($field["value"] as $k => $v)

{{$v['name']}}

            {{Form::checkbox('field_object['.\App\Helpers\Helper::getMongoIDString($v['_id']).']', $v["default"], array("class" => "form-control"))}}

    @endforeach

A: If you only expect one level of recursion on the values, then it's a simple @if check:
@foreach($fields as $field)
    @if(is_array($field->value))
        @foreach($field->value as $key => $value)
            {{$value}}

        @endforeach
    @else
        {{$field->value}}
    @endif
@endforeach


text:
Q: Is python site manual totally generated by pydoc? I tried pydoc to some internal package but the output html is far different from the site version. So I wondered how to generate the doc just like the site document. Or there has to be done by manually tweak and edit
thanks a lot

A: the python site doc is generated using Sphinx
Look here
You can see the line 'Created using Sphinx 1.0.7. ' written at end of http://docs.python.org/index.html page

A: Yes python doc is created from sphinx you can check the "Project Using Sphinx" https://www.sphinx-doc.org/en/master/examples.html.


text:
Q: Relax ssh rate-limit rules for certain ip addresses We've written some tools to automate common development tasks. One tool, for example, ensures all our git repositories are up-to-date. For this to work, our tool needs to connect to our git server and fetch the latest for each repository. We have many git repositories so this tool ends up creating many connections in a short timespan - throwing iptable's rate limit rule and locking us out for a while (not sure how long).
How can I disable this rate-limit for certain IP addresses (like our office)?

A: throttle your requests down is always a better idea than creating hard to maintain exceptions in your security schema.


text:
Q: Can i tell python to do something with a button at a location in a grid that I give it? So I'm wondering if and how I would tell python something like: here's the row and column in which a button is located, now do something to it. This is what I have now.
(Can I input the row and column or something here).config(...)

A: As @Karl mentioned, it would be easiest to just remember where your widgets are, say with a 2d list. However, you can find where a widget has been placed using the grid method using parent.winfo_children() and widget.grid_info(). An example of this is:
def find_widget(parent, row, column):
    widgets = parent.winfo_children()
    for widget in widgets:
        widget_grid = widget.grid_info()
        if widget_grid["column"] == column and widget_grid["row"] == row:
            # You have found the widget in your coordinates
            return widget
    else:
        # No widget matches your coordinates
        return None

This will only work if all the widgets in your grid have the same parent, so using a frame would likely be ideal. You can then configure your returned widget however you need


text:
Q: Where is the room with the stargate? I remember walking into a room and dot saying something along the lines of "I can't believe it! A working stargate", but I didnt go through it because I didn't know if it was the end. I'm assuming that was the end of the game.
Problem is, I don't know where that room is anymore. The only anticubes I have left are the first person puzzles, which you get after you beat the game.
Where is it? How can I find it again?

A: It's in the "modern temple" area (the 16-cube door), behind the large 32-cube door.

It'll show as a large black opening if you've already been inside.

A: Go back to the first warp gate, then through the purple door where you came in for the first time to the area with the 4, 8 and 16 cube doors. The under-construction 'big-head' village (or the 'modern temple') is though the 16 cube door.
The 4 door leads to your 2D ancestors village (according to the evolution chart in the class room). The 8 door to the neon city.
Dot says "I can't believe it! A working stargate" in the under-construction big-head village because there's also a space-infected one in the ruined big-head village.
Also in that village are 4 murals in another room showing:

*

*The gate being started

*The gate being built

*The finished gate with 4 big-heads wear a fez each.

*The gate destroyed by space holes (as you see it in the ruined village)


text:
Q: Reset outlook to auto selects when sending email from outlook it populates a list of suggestions.  We moved email servers recently so some of the addresses are no longer valid.  How can I have the "suggestions" cleared.

A: Assuming that you are referring to the autocomplete function of the TO: field in Outlook, that data is kept locally on a per user and per profile basis.
Typically it is found in a User's directory as an NK2 file. By defaults it is usually named outlook.nk2. This file is profile specific (Outlook profile) and contains all previously used sent addresses.
If you delete the file, the next time Outlook is started a new one will be created and will begin collecting sent addresses again.
On XP it is found in C:\Documents and Settings\UserID\Application Data\Microsoft\Outlook
On Win7 it is found in C:\Users\UserID\AppData\Roaming\Microsoft\Outlook
You can also selectively remove items from the autocomplete by beginning to type a name you want to remove in the TO: field and when it displays, arrow over it with the keyboard and press the "Delete" key.


text:
Q: Spring Data @OneToMany(fetch=FetchType.EAGER) working as select query mode I attached below my codes. load children one by one, when i get all parent entities. How to solve it?

Parent Entity Class. It has 3 attributes as id, name, and children. children attribute load eagerly. because i need parent object with its children.
    @Entity
    @Table(name = "parent")
    public class Parent {
        @Id
        private int id;

        private String name;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", fetch = FetchType.EAGER, orphanRemoval = true)
        private List<Child> children;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public List<Child> getChildren() {
            return children;
        }

        public void setChildren(List<Child> children) {
            this.children = children;
        }

        public String getName() {
            return name;
        }

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

Child Class. It has 3 property such as id, name and parent. parent property load as lazy mode. because i never wants child object with its parent object.
    @Entity
    @Table(name = "child")
    public class Child {
        @Id
        private int id;

        @Column(name = "name")
        private String name;

        @JsonIgnore
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "parent", referencedColumnName = "id")
        private Parent parent;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        public Parent getParent() {
            return parent;
        }

        public void setParent(Parent parent) {
            this.parent = parent;
        }
    }

I try to get all parents using below code.
    protected List getAll(){
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            entityManager.getTransaction().begin();
            List<Parent> objects = entityManager.createQuery("Select o from Parent o", Parent.class).getResultList();
            entityManager.getTransaction().commit();
            entityManager.close();
            return objects;
        }

I expect only one join query. but hibernate call queries one by one. It getting n+1 query problem.
    Hibernate: select parent0_.id as id1_8_, parent0_.name as name2_8_ from parent parent0_
    Hibernate: select children0_.parent as parent3_0_0_, children0_.id as id1_0_0_, children0_.id as id1_0_1_, children0_.name as name2_0_1_, children0_.parent as parent3_0_1_ from child children0_ where children0_.parent=?
    Hibernate: select children0_.parent as parent3_0_0_, children0_.id as id1_0_0_, children0_.id as id1_0_1_, children0_.name as name2_0_1_, children0_.parent as parent3_0_1_ from child children0_ where children0_.parent=?
    Hibernate: select children0_.parent as parent3_0_0_, children0_.id as id1_0_0_, children0_.id as id1_0_1_, children0_.name as name2_0_1_, children0_.parent as parent3_0_1_ from child children0_ where children0_.parent=?

A: JPA doesn't provide any specification on mapping annotations to select fetch strategy.
Use JOIN FETCH to fetch both root entities and their mapped entity/collection in one query which solved N+1 query problem.Like
SELECT distinct p FROM Parent p LEFT JOIN FETCH p.children


text:
Q: Schedule job with multiple triggers in Quartz.net I need to run job on 2 different schedules (morning and afternoon). I know how to run it on one schedule, but not sure how to set it so 2 schedules trigger this job
var saferWatchJobDetail = JobBuilder.Create<SaferWatchProcessor>().Build();
            var swtriggerMorning = TriggerBuilder.Create().WithCronSchedule("0 10 6 ? * MON-SUN *", cs => cs.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"))).Build();
            var swtriggerAfternoon = TriggerBuilder.Create().WithCronSchedule("0 10 13 ? * MON-FRI *", cs => cs.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"))).Build();
            this.scheduler.ScheduleJob(saferWatchJobDetail, swtriggerMorning);

According to documentation it seems like I need to use ScheduleJob override with ISet<ITrigger> but I'm not sure about 2 things:

*

*What is implementing ISet and how do I instantiate this object?

*What is other parameter replace? Not sure how should I use it. And what is the "key"? From documentation:

If any of the given job or triggers already exist (or more
  specifically, if the keys are not unique) and the replace parameter is
  not set to true then an exception will be thrown.

A: granaCoder's answer didn't work for me at all. It kept throwing exceptions. Not sure why.
If you want to use triggerset, which ended up working for me, this is how you do it:
        var triggerSet = new Quartz.Collection.HashSet<ITrigger>();
        var saferWatchJobDetail = JobBuilder.Create<SaferWatchProcessor>().Build();
        var swtriggerMorning = TriggerBuilder.Create().WithCronSchedule("0 10 6 ? * MON-SUN *", cs => cs.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"))).Build();
        var swtriggerAfternoon = TriggerBuilder.Create().WithCronSchedule("0 10 13 ? * MON-FRI *", cs => cs.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"))).Build();
        triggerSet.Add(swtriggerMorning);
        triggerSet.Add(swtriggerAfternoon);
        this.scheduler.ScheduleJob(saferWatchJobDetail, triggerSet, true);


text:
Q: Mercurial: Revert "commit action" changes Suppose I have made a change to a file, hg status show it as modified.
Now I want to commit. Before I can do so I accidentially hg remove my file.
Mercurial now would remove my file on the next commit, hg revert would retain it from removal, my changes would be lost however.
Is exporting a patch and then importing it on top of a MQ my only option to put my file back into "modified" state?

A: I am not sure about that but try adding it back with hg add.
And you can simply export and apply a patch without MQ.


text:
Q: How to reduce loss of Bi-LSTM handwriting recognition model? This is a continuation of the question I asked, question link. This is also a repost from my question on aistackexchange which did not get any attention so posting it here might get more insights on how to solve my problem question in aistack
I am currently training an bi-LSTM model which predicts the handwriting of an individual. I am hitting a current min loss of 1.2 and I think it is not a problem with the model because I copied a model used by a study [DOI: 10.1109/I2CT51068.2021.9418153] this study uses the IAM dataset as training data which is what I am currently using.
The way I am looking at this problem is that maybe my image preparation was not the same as said in the research. I prepared the image by changing the size of the words preserving the aspect ratio copied into a blank black canvas on the center which makes my images normalized to a single size. As said in the study "The built network takes in a variable width image as an input, where the length of the image is sixty pixels". So I think I am doing something wrong here or just misunderstanding somethings. Is it possible maybe that this model accepts images with variable widths or is it just doing what I did? Also the study had a loss of under 1 in just 5 epochs. Which I can hardly hit with mine. And does the image's scale a factor here? if so can I improve it by introducing data augmentation in my dataset? Thanks in advance for answering my queries it will greatly help my project thank you.
A sample of the dataset:

Model: "handwriting_recognizer"
__________________________________________________________________________________________________
 Layer (type)                   Output Shape         Param #     Connected to
==================================================================================================
 image (InputLayer)             [(None, 360, 60, 1)  0           []
                                ]

 Conv1 (Conv2D)                 (None, 360, 60, 64)  1664        ['image[0][0]']

 batchnorm1 (BatchNormalization  (None, 360, 60, 64)  256        ['Conv1[0][0]']
 )

 pool1 (MaxPooling2D)           (None, 180, 30, 64)  0           ['batchnorm1[0][0]']

 Conv2 (Conv2D)                 (None, 180, 30, 64)  36928       ['pool1[0][0]']

 batchnorm2 (BatchNormalization  (None, 180, 30, 64)  256        ['Conv2[0][0]']
 )

 pool2 (MaxPooling2D)           (None, 90, 15, 64)   0           ['batchnorm2[0][0]']

 Conv3 (Conv2D)                 (None, 90, 15, 256)  147712      ['pool2[0][0]']

 Conv4 (Conv2D)                 (None, 90, 15, 256)  590080      ['Conv3[0][0]']

 batchnorm3 (BatchNormalization  (None, 90, 15, 256)  1024       ['Conv4[0][0]']
 )

 pool3 (MaxPooling2D)           (None, 45, 7, 256)   0           ['batchnorm3[0][0]']

 Conv5 (Conv2D)                 (None, 45, 7, 512)   1180160     ['pool3[0][0]']

 Conv6 (Conv2D)                 (None, 45, 7, 512)   2359808     ['Conv5[0][0]']

 batchnorm4 (BatchNormalization  (None, 45, 7, 512)  2048        ['Conv6[0][0]']
 )

 pool4 (MaxPooling2D)           (None, 22, 3, 512)   0           ['batchnorm4[0][0]']

 reshape (Reshape)              (None, 22, 1536)     0           ['pool4[0][0]']

 dense1 (Dense)                 (None, 22, 64)       98368       ['reshape[0][0]']

 dropout (Dropout)              (None, 22, 64)       0           ['dense1[0][0]']

 bidirectional (Bidirectional)  (None, 22, 256)      197632      ['dropout[0][0]']

 bidirectional_1 (Bidirectional  (None, 22, 256)     394240      ['bidirectional[0][0]']
 )

 bidirectional_2 (Bidirectional  (None, 22, 128)     164352      ['bidirectional_1[0][0]']
 )

 dropout_1 (Dropout)            (None, 22, 128)      0           ['bidirectional_2[0][0]']

 label (InputLayer)             [(None, None)]       0           []

 dense2 (Dense)                 (None, 22, 85)       10965       ['dropout_1[0][0]']

 ctc_loss (CTCLayer)            (None, 22, 85)       0           ['label[0][0]',
                                                                  'dense2[0][0]']

==================================================================================================
Total params: 5,185,493
Trainable params: 5,183,701
Non-trainable params: 1,792
__________________________________________________________________________________________________


text:
Q: how to disable datagridview mouse click event for headers in c# I am trying to get value out of datagridview on mouse click event.
Works great until I click on headers in datagridview. I get an error saying:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name:index

I use this code to detect mouse click:
 private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dataGridView1.Rows[e.RowIndex].Index != -1)
            {
                textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            }
            else
            {
                textBox1.Text = "";
            }
        }

"dataGridView1.Rows[e.RowIndex].Index != -1"
  doesn't work and I do not know why.

Any easy solution to disable mouse click event on headers would be great! Thanks!
I also use:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

to select whole column and CellContentClick doesn't work. If I am lucky, CEllContentClick works 3/10 times.

A: Try writing this instead:
private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.RowIndex != -1)
    {
        textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
    }
    else
    {
        textBox1.Text = "";
    }
}


text:
Q: Converting a list of coordinates to point geometry My geopandas df looks like this:
   events   datum   pz  ...  dst        Aktenzahl              geometry
0      22  2015.0  204  ...  BSm  BSm/204/30/2015  [16.34203, 48.21717]
1      22  2015.0  202  ...  BSm   BSm/202/8/2015  [16.34189, 48.21719]

As you can see, the geometry column is a list containing longitude and latitude values. Is there an efficient way to convert them to points?
This works but is very inefficient:
pts = gpd.GeoDataFrame(geometry=gpd.points_from_xy(
[df['geometry'][0][0], df['geometry'][1][0]],
[df['geometry'][0][1], df['geometry'][1][1]]))

df["geometry"] = pts
df = gpd.GeoDataFrame(df, crs='epsg:4326').set_geometry('geometry')
df

   events   datum   pz  ...  dst        Aktenzahl                   geometry
0      22  2015.0  204  ...  BSm  BSm/204/30/2015  POINT (16.34203 48.21717)
1      22  2015.0  202  ...  BSm   BSm/202/8/2015  POINT (16.34189 48.21719)

When I put this in a loop I get TypeError: len() of unsized object
for i in range(len(df['geometry'])):
  print(df['geometry'][i][0], df['geometry'][i][1]) # works
  print(gpd.GeoDataFrame(geometry=gpd.points_from_xy(df['geometry'][i][0], df['geometry'][i][1]))) # TypeError: len() of unsized object

Basically I need the inverse of this question.
Reproducible data here:
df={'events': {0: 22, 1: 22}, 'datum': {0: 2015.0, 1: 2015.0}, 'pz': {0: 204, 1: 202}, 'strasse': {0: 'Hernalser Gürtel', 1: 'Hernalser Gürtel'}, 'hnr': {0: 'unter U6', 1: 'unter U6'}, 'dst': {0: 'BSm', 1: 'BSm'}, 'Aktenzahl': {0: 'BSm/204/30/2015', 1: 'BSm/202/8/2015'}, 'geometry': {0: [16.34203, 48.21717], 1: [16.34189, 48.21719]}}

A: I don't know why you want a loop.
df={'events': {0: 22, 1: 22}, 'datum': {0: 2015.0, 1: 2015.0}, 'pz': {0: 204, 1: 202}, 'strasse': {0: 'Hernalser Gürtel', 1: 'Hernalser Gürtel'}, 'hnr': {0: 'unter U6', 1: 'unter U6'}, 'dst': {0: 'BSm', 1: 'BSm'}, 'Aktenzahl': {0: 'BSm/204/30/2015', 1: 'BSm/202/8/2015'}, 'geometry': {0: [16.34203, 48.21717], 1: [16.34189, 48.21719]}}
df = pd.DataFrame(df)
df.geometry = gpd.points_from_xy(df.geometry[0], df.geomety[1])
gdf = gpd.GeoDataFrame(df, geometry='geometry', crs = 'epsg:4326)

All coordinates have been changed to points.
Do you think this is really inefficient?

Update
sorry, I have a mistake.
I think the solution you want is this.
df.geometry = gpd.points_from_xy(pd.DataFrame(df.geometry.to_list())[0], pd.DataFrame(df.geometry.to_list())[1])


text:
Q: Join a value onto an existing data.table without an exact match (matching within an interval) I have a column in a data.table (DT1) that is a decreasing count (let's say pol_count), and another column for the average age in a population (say AverageAge). I am trying to take my value of pol_count (say 400) and my value of AverageAge (say 85) and match them to an interval within a table called FactorFile.
Here is a glimpse of FactorFile:
Count_Greater_Than  Age_Less_Than   Months  Factor
100                 80              12      1
85                  82              16      0.85
65                  84              20      0.65
45                  86              24      0.45

In this instance, pol_count is > 100 so it would return the third column's (Months) value of 12, and AverageAge is < 86 but > 84 so it would return 20. I then need another column to take the max, so final answer is 20. Finally, a column for the Factor associated with 20 which is 65%.
I'm not sure how to join on a table without using exact matches. Basically I want a VLOOKUP with the last argument as TRUE, to pull the closest value to the supplied lookup value.
I've tried using the package fuzzyjoin, here is my statement. It runs, but nothing seems to happen to my data.table:
fuzzy_left_join(DT1, FactorFile, by = c("AverageAge" = "Average_Age_Less_Than"), match_fun = `<=`)

Any tips on how to use fuzzyjoin correctly or an easier way to make this join happen? To summarize, I'm trying to take two columns in DT1, and return both a Months column and Factor column onto DT1, by joining on FactorFile.
Thanks!

A: Maybe something like this:
DT1[, c("M1", "F1") :=
    FactorFile[.SD, on=.(Count_Greater_Than=pol_count), roll=Inf, .(Months, Factor)]
]

DT1[, c("M2", "F2") :=
    FactorFile[.SD, on=.(Age_Less_Than=AverageAge), roll=Inf, .(Months, Factor)]
]

DT1[, c("M", "Fac") := {
        mm <- pmax(M1, M2)
        .(mm, fifelse(mm==M1, F1, F2))
    }]

output:
   pol_count AverageAge M1 F1 M2   F2  M  Fac
1:       400         85 12  1 20 0.65 20 0.65

data:
library(data.table)
DT1 <- data.table(pol_count=400, AverageAge=85)
FactorFile <- fread("
Count_Greater_Than  Age_Less_Than   Months  Factor
100                 80              12      1
85                  82              16      0.85
65                  84              20      0.65
45                  86              24      0.45")


text:
Q: How to solve 'Error in grid.call.Graphics' when saving a flextable I have a function in a container that takes data and generates a line plot, and saves the result as a png.
There are about 50 companies and saves 10 images for each, so it loops through each one and generates 500 pngs.
Without fail, on the 11th company and 5th flextable, I get the following error

This error is only raised on the hosted container. When I run the container on a local host, I do not receive this error and it processes fine.
google-fu has not helped me so far, so I would like to know if anyone has encountered this error before, and how it might be dealt with. TIA
the method of saving the flextable is:
save_as_image(ft,
                   path = f,
                   zoom = 3 ,
                   webshot = "webshot2") # save flextable as png


text:
Q: If I include images as resources in my Visual Studio project, do these images get compiled into the executable? What I mean is, if I want to compile and distribute my program, do I have to include folders in the download that have the images and then link a relative path to those folders in my code? Or if I include the images as a resource, is their data saved in the machine code of the program, allowing me to just handout out an executable?

A: Resources are embedded into the EXE / DLL.

*

*MSDN: Using Resources

A: Windows uses a resource section so technically its not part of the machine code, it just handled elsewhere within the exe.
Resource compilation is by default unconditional ( opposed to some compiler/linker settings when code only gets compiled/linked when it's used ) so if you specify the binary file as a resource the final exe will have it regardless if it's being used or not.
Later you can use the windows resource functions windows resource functions to get the data, altho keep in mind that its just data if it's a resource so you have to explicitly write it to the disk and then you can executed it, not from the resource itself.


text:
Q: Touch underlying view with nextResponder Currently I am trying to recreate the Twitter (iPad) type control. Mostly because all the versions available online are not really working for the type of application I am developing, and I think I can do better of course ;) (but it is harder than I thought).
What I want:

*

*Flexible positioning of the view controllers I add to the control

*No need to change my current view controllers when I want to use them in my control (mainly because I use the view controllers in the iPhone and the iPad version).

*Being able to drag the view controllers around, but still keep al functionality in the view controllers.

What I currently got:

*

*Good positioning on the view controllers, when they are added to my control.

*Able to drag the view controllers around, according to the rules I have set (maximum x position etc)

My problem is that when I add a UITableViewController, I want to be able to drag it around AND keep the functionality of scrolling and selecting cells in the table.
My current solution is, that when a view controller is added to my control, I add a subview to it (with the same size of the view controller) which accepts all the touches. These touches are then send to the control, by using a delegate and calling methods on it. This works well, accept that when I add a subview to my UITableViewController, there is some weird behavior. Scrolling up and down still works in the UITableViewController, but these touches aren't detected by the View on top of the UITableViewController. Selecting cells in the table does not work anymore, because these touches are taken by the overlaying UIView.
I add the overlaying UIView to the UITableViewController like this:
SNOverlayView* layover = [[SNOverlayView alloc] initWithFrame:CGRectMake(0,0, controllerWidth, self.frame.size.height)];
layover.delegate = self;
[controller.view addSubview:layover];
[layover release];

My custom overlay UIView contains a couple of these methods, for all the touch (began, ended, cancelled and moved) methods:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([delegate respondsToSelector:@selector(overlayTouchesBegan:touches:event:)])
    [delegate overlayTouchesBegan:self touches:touches event:event];

    NSLog(@"%@", self.nextResponder);

    [self.nextResponder touchesBegan:touches withEvent:event];
}

From what I understand from the documentation, the call to the nextResponder, should make sure that the TableView below my view also receives the touches. But these methods only get triggered when I touch the screen once OR slide sideways. Sliding from up to down does not trigger these methods and touching a cell does not trigger the didSelectRowAtIndexPath from the UITableViewController. The self.nextResponder in this method is a UITableView (which is outputted by the NSLog in that method).
I am misunderstanding the nextResponder part? Isn't this possible when not modifying my UITableViewController?
EDIT: I updated the structure which I add to my main UIView containing all ViewControllers:
|- Root UIView (1)
|-- Containment UIView which detects touches (2)
|---- UITableViewController (3)

The problem is that now my containment view (2) does not detect touches. I will try to update my code to make it more like the structure mentioned below:
|- Root UIView (1)
|-- Containment UIView (2)
|---- UIView detecting touches (4)
|---- UITableViewController  (3)

But I am not sure how I can get the UIView to detect touches. because when I add the UITableViewcontroller (3) to my containment UIView (2) it will be put on top of the UIView detecting the touches (4) and therefor 'stealing' the touches. I would rather change the order of (4) and (3).

A: Are you adding a subview to a UITableView? This is dangerous, because it will scroll with the cells (UITableView is a sub-class of UIScrollView), and because the UITableView adds and removes subviews itself too, so you can't control the order that the views are in.
I think your best bet would be to have a view hierarchy like this
- containerView (plain UIView, that your UIViewController loads)
|-- overlayView (catches touches)
|-- UITableView

That being said, I've got a suspicion that UIScrollViews use a different method for grabbing touches to other UIViews (i.e. not touchesBegan: etc.).


text:
Q: 'rails' command creates directory with /vendor/rails which uses wrong version of rails For some reason when I run rails command, it installs 2.2.3 version of Rails in /vendor/rails and webbrick uses that version instead of 2.3.5 which is installed as a gem.
If I delete that, then it uses the right directory. I remember using git submodule once, but I don't think that has anything to do with this.
How can I correct this? Thanks
Edit:
I never installed Rails 2.2.3. Although I do vaguely remember using git submodule, if that helps anyone.

A: Check your local gems, and your system gems.  Perhaps, you have it 2.2.3 installed in your user's bin.

A: Try running:
rake rails::unfreeze

What's happening is 2.2.3 is getting frozen into your vendor directory.
As to why that's happening, I'm not sure.  Be sure that you actually have 2.3.5.  And unfreezing/refreezing should fix it.
rake rails::freeze::gems

A: does the rails gem get vendored at the same time you create the app?  that seems very strange if so.
if you are on linux or mac then it's possible you have something in your bash profile that's overriding the rails command.  to be honest it sounds like a rails template is being run when you create your app....
failing that is it perhaps possible that you have something like 'instant rails' running on your machine and it's taking control instead of the rails gem?
very strange.  what OS are you on?  sometimes it helps to try creating a new user profile and seeing if you get the same problems when you login to that account....


text:
Q: Помогите с рекурсией плиз Есть двумерный массив $categories, в котором содержатся массивы с ключами name, category_id и parent_id. Нужно как-то с помощью рекурсии создать новый массив $category_id, в который добавлять category_id до тех пор, пока parent_id не будет нулем. Здесь $this->data['link'] это ссылка на конечную подкатегорию, у которой может быть сколько угодно родительских категорий. Для этого собственно говоря и нужен массив $category_id, чтобы знать айдишники всех родительских категорий. Надеюсь что понятно объяснил...))
$category_id = [];
foreach ($categories as $category) {
        if ($category['name'] == $this->data['link']) {
            array_push($category_id, $category['category_id']);
            function find() {
                if ($category['parent_id'] != '0') {
                    foreach ($categories as $category) {
                        if ($category['parent_id'] == $category['category_id']) {
                            array_push($category_id, $category['category_id']);
                        }
                        find();
                    }
                }
            }
        }
    }

A: Всем спасибо, оказалось все намного проще: на этапе формирования ссылки я создавал массив со всеми родителями выбранной категории
$arr = explode(' > ', $this->data['link']);

соответственно для решения моего вопроса нужен был вот этот простой код:
 $category_id = [];
    for ($i = 0; $i < count($categories); $i++) {
        for ($j = 0; $j < count($arr); $j++) {
            if ($categories[$i]['name'] == $arr[$j]) {
                $category_id[] = $categories[$i]['category_id'];
            }
        }
    }


text:
Q: How to expose kafka metrics to /actuator/metrics with spring boot 2 I was looking a while and didn't seem to find the answer.
I'm using Spring boot 2, Spring Kafka 2.1.4 and I want to see the kafka consumer metrics in the /metrics endpoint of spring boot actuator.
What I don't understand is  - should I implenemt the exposure myself or is this comes out-of-box in boot 2 ?
If I to implement this my self, what is the best way to do it?

A: Targeted for micrometer v1.1.0 is the KafkaConsumerMetrics implementation of MeterBinder. This should expose the kafka consumer metrics you're looking for.
Source Reference:
https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java

A: add this config works for me:
spring.jmx.enabled=true

A: You are right, there is no out-of-the-box one. You don't have choice unless to implement your own MeterBinder. For the Apache Kafka Consumer metrics per se, you should inject a KafkaListenerEndpointRegistry and call its getListenerContainers() and use their metrics() to bind to the provided MeterRegistry.
When you come up with something, feel free to contribute the solution back to Spring Boot.

A: This works for me(For Spring Boot 2.3.0.RELEASE and above):
@Autowired
private MeterRegistry meterRegistry;

@Bean
public ConsumerFactory<Object, Object> consumerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class);
    props.put(ErrorHandlingDeserializer.KEY_DESERIALIZER_CLASS, JsonDeserializer.class);
    props.put(ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS, JsonDeserializer.class);

    //More code here

    DefaultKafkaConsumerFactory<Object,Object> cf = new DefaultKafkaConsumerFactory<>(props);
    cf.addListener(new MicrometerConsumerListener<>(meterRegistry));

    return new DefaultKafkaConsumerFactory<>(props);
}

build.gradle
implementation 'io.micrometer:micrometer-registry-prometheus'

Metrics will be available at /actuator/prometheus/kafka_consumer_<metric-name>.


text:
Q: How to install Velero on premise I am following this tutorial to install Velero to backup my cluster.
I have successfully installed the Minio the deployment but I am encountering a problem when installing Velero itself.
When I run the command:
    velero install \
--provider aws \
--plugins velero/velero-plugin-for-aws:v1.0.0 \
--bucket velero \
--secret-file ./credentials-velero \
--use-volume-snapshots=false \
--backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.velero.svc:9000

I keep getting this error:
CustomResourceDefinition/backups.velero.io: attempting to create resource
An error occurred:
Error installing Velero. Use `kubectl logs deploy/velero -n velero` to check the deploy logs: Error creating resource CustomResourceDefinition/backups.velero.io: the server could not find the requested resource

When I type the kubectl logs command, I get this:
ubuntu@kubemaster:~$ kubectl logs deploy/velero -n velero
Error from server (NotFound): deployments.apps "velero" not found

Am I missed something?

A: In the article you mentioned you fetch and install minio 1.1.0 version.
curl -LO https://github.com/heptio/velero/releases/download/v1.1.0/velero-v1.1.0-linux-amd64.tar.gz
tar -C /usr/local/bin -xzvf velero-v1.1.0-linux-amd64.tar.gz
export PATH=$PATH:/usr/local/bin/velero-v1.1.0-linux-amd64/

At the same time you use aws plugin in command --plugins velero/velero-plugin-for-aws:v1.0.0

As per comment in Error in creating CRD on openshift 3.11:

for v1.1 you don't need to use an external AWS plugin, it was still
in-tree. Please make sure you're following the correct docs for the
Velero version you're using: https://velero.io/docs/v1.1.0/aws-config/

By opening documentation for 1.1.0 aws configuration you see that no plugin argument was used in velero install command (by the way in medium article also).
velero install \
    --provider aws \
    --bucket $BUCKET \
    --secret-file ./credentials-velero \
    --backup-location-config region=$REGION \
    --snapshot-location-config region=$REGION

So it could be version issue. Think you should either use newer velero versions either configure aws without plugin according to old documentation.


text:
Q: Get EAN by Amazon ASIN Amazon API is so complex and huge, so I've spent some time to understand how to get EAN by ASIN or even if it is possible or not. I was trying to use GetItems and it works but ItemInfo doesn't have EAN field.
Any help, please!


text:
Q: False Positive in SonarQube Hibernate Transaction Consider the following code:
Transaction tx = null;

try {
  Session currentSession = getCurrentSession();
  tx = currentSession.beginTransaction();
} catch (HibernateException e) {
   if (tx != null) {
     tx.rollback();
   }
}

SonarQube with the command-line version of Sonar Scanner (2.5.1) - both the latest versions that I downloaded just the other day, produce the following Blocker Issue:
Change this condition so that it does not always evaluate to "false"
It occurs on the if (tx != null) check above. But, it is possible that if the call to getCurrentSession() fails, that tx is null...


text:
Q: Merging when master is behind So I have branchA, branchB, and master. branchB was many commits behind master. I merged branchB into branchA and then branchA into master. This successfully merged the feature I added in branchA. However, since branchB was so much behind, it removed other coworkers' feature that were already merged into master. We ended up reverting branchA.
My question is how do I get branchA's changes without deleting other features.

A: You can update your branches by rebasing the master into your branch


text:
Q: Get next non consecutive ones binary number I have been doing a question in which i have been given a number lets say 5 ( 101) not having any consecutive one, i  need to find the next number which have non consecuitve ones.
Next is 6 (110), 7 (111), 8 ( 1000). so my answer should be 8.
Can anyone tell me the approach , other than going to next number and see consecutive bits.

A: A fast way to solve this problem is to scan the bits of the number until you find two consecutive 1s. When this happens, you want to fix it. In other words, you want to make a number that is slightly greater than the current number. How much greater, exactly?
Consider the bits on either side of the 11:
...11...

We'll say that 11... is the suffix of the current number. Imagine that we keep adding 1 to the suffix until the 11 goes away. When is that going to happen? Well, the 11 isn't going to turn into 10 or 01, because that would make it smaller. We are only increasing the number.
The 11 is only going to disappear when the suffix becomes 00.... The smallest such suffix consists of all zeros. Thus, when we encounter a 11, we can immediately zero it out and all bits that come after it. Then we add 1 to the bits that are to the left of the suffix.
For example, consider the rightmost 11 in this number:
        1000101011000100
                ^^
        suffix: 11000100
prefix: 10001010

We zero out the suffix and add one to the prefix:
        suffix: 00000000
prefix: 10001011
result: 1000101100000000

Now we continue our search toward the left, looking for the next 11.
The following function shifts right to zero out the suffix, adds one to the prefix, and shifts left to restore the prefix to its position.
int next(int x) {              /* Look for a number bigger than x. */
  x += 1;
  int mask = 3,                /* Use the mask to look for 11.     */
      pos = 2;                 /* Track our location in the bits.  */
  while (mask <= x) {
    if ((mask & x) == mask) {  /* If we find 11, shift right to    */
      x >>= pos;               /*  zero it out.                    */
      x += 1;                  /* Add 1, shift back to the left,   */
      x <<= pos;               /*  and continue the search.        */
    }
    mask <<= 1;                /* Advance the mask (could advance  */
    pos += 1;                  /*  another bit in the above case). */
  }
  return x;
}

This approach performs a constant number of operations for each bit of the input, making it quite a bit faster than the brute-force approach. Formally, the running time is logarithmic in the size of the input.
Below is a complete program that takes the value of x on the command line.
#include <stdlib.h>
#include <stdio.h>

void display(int x) {
  int p = 1;
  while (p < x) {
    p <<= 1;
  }
  while (p != 0) {
    printf("%d", (x & p) ? 1 : 0);
    p >>= 1;
  }
}

int next(int x) {              /* Look for a number bigger than x. */
  x += 1;
  int mask = 3,                /* Use the mask to look for 11.     */
      pos = 2;                 /* Track our location in the bits.  */
  while (mask <= x) {
    if ((mask & x) == mask) {  /* If we find 11, shift right to    */
      x >>= pos;               /*  zero it out.                    */
      x += 1;                  /* Add 1, shift back to the left,   */
      x <<= pos;               /*  and continue the search.        */
    }
    mask <<= 1;                /* Advance the mask (could advance  */
    pos += 1;                  /*  another bit in the above case). */
  }
  return x;
}

int main(int arg_num, char** args) {
  int x, y;
  if (arg_num != 2) {
    printf("must specify a number\n");
    return 0;
  }
  x = atoi(args[1]);
  y = next(x);
  printf("%d -> %d\n", x, y);
  display(x);
  printf(" -> ");
  display(y);
  printf("\n");
  return 0;
}

A: Ok I compiled and tested this, so I know this works.  First, the answer to the original problem.  It can be done quickly in constant time using some bit tricks:
int getNext(int x)
{
    int invx = ~x;
    int dbl0 = invx & (invx >> 1);

    dbl0 =  (dbl0 & -dbl0);
    x   |=   dbl0;
    x   &= ~(dbl0 - 1);
    return x;
}

The idea behind this is that you need to find the rightmost 00 pattern in the number.  Everything to the right of the 00 pattern must be of the form 10101010... because we know there are no other 00 patterns and no other 11 patterns to the right (the given number does not have any consecutive 1s).  Once you find the rightmost 00 pattern, you can set the lower zero to one and clear all the other bits below that to zero.  Example:
1001010001010010101010
             ^  = lowest 00 pattern

1001010001010100000000
             ^ set this bit and clear all bits to its right

The bit trick steps are as follows:
1001010001010010101010 = x
0110101110101101010101 = ~x = invx (flip the bits because we are looking for 0s)
0010000110000100000000 = invx & (invx >> 1) = dbl0 (find all 00 patterns)
0000000000000100000000 = dbl0 & -dbl0 (isolate the lowest 00 pattern)

Now on to the general problem posed by Michael Laszlo.  This can be solved in constant time only if a CLZ (count leading zero) builtin is allowed.  Otherwise, it takes log(n) time to isolate the high bit of a number.  The basic idea is the same as before.  The only difference is that instead of finding the lowest 00 pattern, we must find the lowest 00 pattern that is higher than the highest 11 pattern.  In other words, we must find the highest 11 pattern first and then search bits higher than that for a 00 pattern.
int getNextGeneral(int x)
{
    int dbl0 = 0;
    int dbl1 = (x & (x >> 1));
    int invx = 0;

    // Find the highest 11 pattern in x.  If we find such a pattern,
    // we write 1s to all bits below the 11 pattern.  This is so that
    // when we will be forced to find a 00 pattern above the highest
    // 11 pattern.
    if (dbl1 != 0) {
        // Assumes 32 bit integers.  Isolates high bit in dbl1.
        dbl1 = 1 << (31 - __builtin_clz(dbl1));
        // Write all 1s to x, below the highest 11 found.
        x |= dbl1 - 1;
    }

    // This code is the same as before.
    invx = ~x;
    dbl0 = invx & (invx >> 1);

    dbl0 =  (dbl0 & -dbl0);
    x   |=   dbl0;
    x   &= ~(dbl0 - 1);
    return x;
}

A: Here's an alternative method, based on roughly the same idea as the CLZ method, except since it works from right to left instead of left to right it can take several steps. Unlike the other right to left method posted, it will visit only the problem sites, instead of iterating over all bits.
The formula x & (x >> 1) mentioned in the comments makes a mask of all the bits that are 1 and have a 1 immediately to the left of them. So the lowest 1 bit in that mask is the "first problem", which we can solve as follows: (choose uint to be some kind of unsigned type)
uint m = x & (x >> 1);
uint lowest = m & -m;    // get first problem
uint newx = (x + lowest) & (lowest - 1); // solve it

The last line increments the 11 found and zeroes out everything to the right of it.
If there is no problem (that is, m = 0), then lowest = 0 also, so in the last line, nothing is added and you AND with all-ones (I would prefer to call that -1, but this is a C question so someone would complain about that). In short, if 11 does not occur, the number is unchanged.
That would have been great in case we could have used this without any control flow, but we can't - fixing one problem may cause one further to the left (or it may already have been there). So this has to be looped until there are no more problems, for example like: (not tested)
uint m = x & (x >> 1);
do {
    uint lowest = m & -m;
    x = (x + lowest) & (lowest - 1);
    m = x & (x >> 1);
} while (m);

Obviously it expects the original number plus 1 as input, otherwise it can return the same number.

And here's a way to get rid of the CLZ in the beautiful CLZ method by JS1. Rewriting CLZ almost always results in a "suffix-OR", and indeed it does this time.
The point was to isolate the highest 1 and then subtract one, that can be done directly (ie without clz and shift) like this: (the loop here is called "suffix-OR")
cbl1 >>= 1;
for (int i = 1; i < sizeof(something) * CHAR_BIT; i <<= 1)
    dbl1 |= dbl1 >> i;

Not a real loop of course, it would be silly not to unroll it (basically it's going to be either 5 or 6 iterations in practice).
You could count it as constant time or not, depending on what takes your fancy - if you want to consider the size of the type you're working with a variable, then this thing takes O(log n) steps.