text:
Q: How I should behave when a change-of-variables (integrals) is not injective? ##What follows is how my doubt was born. If you want, you can directly read my true question at "the bottom"##
Let's suppose to have a domain like this: $\Bbb V=\{(x+1)^2+(y-2)^2+(z+3)^2\le1\}$ and I want to evaluate $\int_{\Bbb V}1\,dx\,dy\,dz$.
It's obvious that a good change-of-variables is $\Phi:(u,v,w)\rightarrow(x,y,z)$, $\begin{cases}(x+1)=u \\ (y-2)=v \\ (z+3)=w\end{cases}$
Such a $\Phi$ is an injective function, so it doesn't cause any trouble to me: $\Bbb V$ is simply rewritten as $\Bbb V^*=\{u^2+v^2+w^2\le1\}$ and the integral is done simply as $\int_{\Bbb V^*}1\,du\,dv\,dw$

Now take the domain $\Bbb V = \{x^2 + y^4+z^2\le1\}$ and $\int_{\Bbb V}1\,dx\,dy\,dz$.
I would like to transform it into a sphere through $\Phi:(u,v,w)\rightarrow(x,y,z)$, $\begin{cases}x=u \\ y^2=v \\ z=w\end{cases}$
But $\Phi$ is NOT an injective function, so I have to separate the cases $(y\le0 ,\ y\ge0)$ that would result into a new domain $\Bbb V^-=\{u^2+v^2+w^2\le1,\ v\le0\}\, \bigcup\, \Bbb V^+=\{u^2+v^2+w^2\le1,\ v\ge0\}$.
Anyway, I'm really confused about how $(v\le0 ,\ v\ge0)$ came; moreover the right new-integral should be:
$$\int_{\Bbb V^+}\frac{1}{2 \sqrt{v}}\,du\,dv\,dw \quad + \quad \int_{\Bbb V^-}\frac{1}{2 \sqrt{-v}}\,du\,dv\,dw$$
And I am even more confused about the signs under these roots...
The only way I found to understand "how" is to apply different change-of-variables for each case: $$y\ge0 \rightarrow\begin{cases}x=u \\ +\ y^2=v \\ z=w\end{cases} \qquad y\le0 \rightarrow\begin{cases}x=u \\ -\ y^2=v \\ z=w\end{cases}$$
But that method doesn't seem too legit to me..
=============
Then I noticed that $(v)$ as independent variable can assume both positive and negative values, instead the function $(y^2)$ can assume only positive values; so the right change-of-variables is $\Phi:(u,v,w)\rightarrow(x,y,z)$, $\begin{cases}x=u \\ y^2=|v| \\ z=w\end{cases}$
That $\Phi$ also doesn't cause any trouble to me: $\Bbb V$ is simply rewritten as $\Bbb V^*=\{u^2+v^2+w^2\le1\}$ and the integral is done simply as $\int_{\Bbb V^*}\frac{1}{2 \sqrt{|v|}}\,du\,dv\,dw$; and that method seems much more legit to me.
Furthermore that method does't cause any confusion to me, because it's a simply observation about the $\Phi$ I choose and it has nothing to do with the domain $\Bbb V$, I guess.

What really caused me trouble is that exercise:
Consider the domain: $\Bbb D = \{1\le x\cdot y \le 2 ,\, 1\le \frac{x}{y} \le2\}$, then evaluate the integral: $\int_{\Bbb D}1\,dx\,dy$.
I tried the change-of-variable $\Phi:(u,v)\rightarrow(x,y)$, $\begin{cases}x \cdot y=u \\ \frac{x}{y}=v\end{cases}$
But such a $\Phi$ is clearly not injective, so I have to separate the cases. But, at this point, I get confused about what really means "separate the cases"...
Eventually I noticed that the domain provides the information $(x \cdot y \ge 0 ,\ \frac{x}{y} \ge 0)$, instead $[(u), \ (v)]$ as independent variables can assume both positive and negative values; so I thought the right change-of-variables should be:
$\Phi:(u,v)\rightarrow(x,y)$, $\begin{cases}x \cdot y=|u| \\ \frac{x}{y}=|v|\end{cases}$
But $\Bbb D^*=\{1\le|u|\le2,\ 1\le|v|\le2\}$ isn't yet the right domain.. I got really confused about, and I thought the problem was that that observation is "$\Bbb D$-dependant" and NOT (like above) "$\Phi$-dependant".
Eventually, I found that writing such a $\Bbb D^*$ I was losing the information that $[(u) ,\ (v)]$ can't change their sign independently of each other: since $(u \simeq x \cdot y) ,\ \left(v \simeq \frac{x}{y}\right)$, then they must have the same sign. Thus the right domain is: $\Bbb D^*=\{1\le|u|\le2,\ 1\le|v|\le2\ ,\ u \cdot v \ge 0\}$, and the integral become: $\int_{\Bbb D^*}\frac{1}{2 |v|}\,du\,dv$. This is correct.
Therefore, this method seems a bit weird to me because is strictly dependant by the domain $\Bbb D$, and not by the chosen $\Phi$, with a loss of generality.

##The bottom##
Is there a GENERAL theory which is "$\Phi$-oriented" and doesn't take care of the domain?
(If doesn't) How I should recognize the behavior of the domain transformation?
– I mean, is there any useful tips or some common situations that I can easily recognize?–

A: You say you have a problem with functions that are not injective,
but I think what you really have trouble with is how to define a function.
Suppose we write
$$\Phi:(u,v,w)\rightarrow(x,y,z),\ \begin{cases}
x=u, \\ y^2=\lvert v\rvert, \\ z=w.\end{cases}$$
What is this? It is not an "injective function" because it is not yet a function of any kind. A function must have a domain and a codomain and must associate a unique object in the codomain with each object in the range.
Suppose we say the domain is $\{(u,v,w) : u^2 + v^2 + w^2 \leq 1\}.$
What does $\Phi$ say when $v = \frac14$? We have two solutions for $y^2 = \frac14$,
namely, $y = \frac12$ and $y = -\frac12.$
Which one of these is uniquely associated with $v = \frac14$?
The formula does not say, so it does not define a function.
We could fix this by saying $y = \sqrt{\lvert v\rvert}.$
The square root function $\sqrt{\cdot}$ dictates that we always take the positive solution for $y$ in $y^2=\lvert v\rvert.$
We also have the concern that
$\left\lvert-\frac14\right\rvert = \left\lvert\frac14\right\rvert,$
so the formula for $\Phi$ does not tell us how we should get a different value of $y$ when $v = -\frac14$ than we do when $v = \frac14$.
The previous "fix" using $\sqrt{\cdot}$ does not help at all;
it merely ensures that the function is not injective.
You actually were much closer to a legitimate definition of $\Phi$ when you did it by cases.
Piecewise definitions of functions (defining the function with one formula in one case, and a different formula in another case) are completely and totally legitimate.
It is also completely and totally legitimate to divide a domain into two pieces whose intersection has measure zero and integrate over the two pieces separately.
The only thing that this definition "by cases" was missing was a way to assign the value of $y$ uniquely for each value of $v$ in such a way that you produce all the $y$-values you need and never map two distinct values of $v$ to the same $y$-value.
A way you can do that is to say
$$ y = \begin{cases} \sqrt{v} & v \geq 0, \\
-\sqrt{- v} & v < 0. \end{cases} $$
Now you get one and only one value of $y$ for each value of $v,$
and never map two distinct values of $v$ to the same value of $y.$
This would then enable you to legitimately integrate each piece of the domain,
$\Bbb V^+$ and $\Bbb V^-$, resulting in the integral
$$\int_{\Bbb V^+}\frac{1}{2 \sqrt{v}}\,du\,dv\,dw \quad +
 \quad \int_{\Bbb V^-}\frac{1}{2 \sqrt{-v}}\,du\,dv\,dw.$$
But notice: in $\Bbb V^+,$ you always have $v \geq 0,$ so $\lvert v\rvert = v.$
So the first integral in the sum can just as well be written
$$\int_{\Bbb V^+}\frac{1}{2 \sqrt{\lvert v\rvert}}\,du\,dv\,dw. $$
On the other hand, in $\Bbb V^-$ you always have $v \leq 0,$ so
$\lvert v\rvert = -v.$
Therefore the second integral in the sum can just as well be written
$$\int_{\Bbb V^-}\frac{1}{2 \sqrt{\lvert v\rvert}}\,du\,dv\,dw. $$
In short, if we write the integrands in this fashion, using
$\lvert v\rvert$ instead of $v$ or $-v,$ the integrands on each piece of the domain are the same. So we can just as well integrate this same integrand over the entire domain:
$$\int_{\Bbb V}\frac{1}{2 \sqrt{\lvert v\rvert}}\,du\,dv\,dw. $$
Notice that this is the same conclusion you leaped to when you tried to define $\Phi$ by the formula $y^2=\lvert v\rvert.$
I say "leaped" because in the second attempt, you never defined $(x,y,z)$ as a function of $(u,v,w)$; you had two values of $y$ that could be associated with two values of $v,$ but nothing to say which value of $v$ mapped to which value of $y.$
The only flaw in your first attempt was in the clarity and presentation of the ideas.
You can simply define the parts of the domain, $\Bbb V = \Bbb V^+\cup\Bbb V^-,$
such that $v \geq 0$ in $\Bbb V^+$ and $v \leq 0$ in $\Bbb V^-,$
then define the mapping $\Phi$ such that $y^2 = v,\ y \geq 0$ in $\Bbb V^+$
and $-y^2 = v, \ y \leq 0$ in $\Bbb V^-.$
If you put together the things you said about $\Bbb V^+$ and $\Bbb V^-$ in a coherent, logical progression, you would have said something like that.
Equivalently, you could say $y = \sqrt{\lvert v\rvert}$ in $\Bbb V^+$
and $y = -\sqrt{\lvert v\rvert}$ in $\Bbb V^-.$

By the way, there is nothing that actually says you must have
$y \geq 0$ in $\Bbb V^+$ and $y \leq 0$ in $\Bbb V^-.$
You could just has easily have $y \leq 0$ in $\Bbb V^+$ and $y \geq 0$ in $\Bbb V^-.$
This is just one of the many arbitrary choices we are allowed to make during a change of variables.
For example, when doing a change of variables for $\{(x+1)^2+(y-2)^2+(z+3)^2\le1\}$
you can just as well say $2-y = v$ rather than $y - 2 = v$;
either one will give you an injective function from the unit ball at the origin to the original domain.

For the example $\Bbb D = \{1\le x\cdot y \le 2 ,\, 1\le \frac{x}{y} \le2\}$,
notice that $x$ can be positive or negative, but $x$ and $y$ must always have the same sign.
Moreover, the domain is already divided into two disconnected pieces,
one containing only positive $x$ and $y,$ the other containing only negative $x$ and $y.$
So it is completely natural that you would look at each of these parts of the domain individually before putting your answer together.

The Big Question
You ask:

Is there a GENERAL theory which is "$\Phi$-oriented" and doesn't take care of the domain?

You are integrating over a domain. The integral is not even defined until you have defined the domain, and you cannot say how to integrate it until you understand the domain well enough to compute the integral over it.
How can you possibly even contemplate a method that doesn't "take care of" the domain?
Some useful things you can do are:
Make sure $\Phi:(u,v,w)\rightarrow(x,y,z)$ is a function.
It helps if you can define the function using only expressions
like $x = \ldots,$ $y = \ldots,$ $z = \ldots,$
with a well-defined, uniquely specified expression on the right hand side of each $=$ sign.
You must still ensure that the right-hand side is defined for every point in the domain.
If you cannot figure out how to do this, but can only see how to define a variable implicitly (as in $xy = u,$ $\frac xy = v$),
then you must take the extra trouble to disentangle all the possible ambiguities to ensure that you have a function.
And splitting the domain is usually a good way to do this.
If you transform to a single integral, make sure $\Phi$ is injective. This is after you ensure that $\Phi$ is a function, of course.
If you divide the domain in pieces, you only need to be sure you have an injective function $\Phi$ on each part.
The integrands you get might not match in the end, and you might not be able to put them back together in a single integral.
This is not a problem; just solve each integral individually and add the results.


text:
Q: Problem with getting a value from a object in sysout, basic JAVA problem I have a few codes and im at the chapter of my class where im learning composition.
I think this is very easy for you guys to fix but right  now im having a hard time on this.
Its about the code in the test src where im trying to put objects together and display the fields of an object.
My System.out.println(tv.getResolution()); is giving me "section7.Resolution@1db9742" while im trying to get the 200,100 int value to display... Can  anyone help me ive been stuck on this for  like 2 hours and couldnt find anything on the internet. Tried to change the return  types etc x.x
public class TV {

private String model;
private Resolution resolution;

public TV(String model, Resolution resolution) {
    this.model = model;
    this.resolution = resolution;
}
public String getModel() {
    return model;
}
public Resolution getResolution() {
    return resolution;
}}

\
public class Room {

private TV tv;
private Bed bed;
private Desk desk;

public Room(TV tv, Bed bed, Desk desk) {
    this.tv = tv;
    this.bed = bed;
    this.desk = desk;
}
public void turnLightsON() {
    roomLighting();
}
private void roomLighting() {
    desk.lamp();
}
public void  getResolution() {
this.tv.getResolution();
}
}

/
public class Resolution {
private int width;
private int height;

public Resolution(int width, int height) {
    this.width = width;
    this.height = height;
}
public int getWidth() {
    return width;
}
public int getHeight() {
    return height;
}}

/
public class Test {

public static void main(String[] args) {

    Bed bed = new Bed(100, 250, "LaBed");
    Desk desk = new Desk(110,175,"Black");
    Resolution resolution = new Resolution(200,100);
    TV tv = new TV("Samsung", resolution);

    Room room = new Room(tv,bed,desk);
    room.turnLightsON();
    System.out.println(tv.getResolution());
    System.out.println(tv.getModel()); }}

A: Resolution is an object and not a primitive type, so when you try to print it, you end up using the default toString() method which returns the class name and a hashcode. Either override the toString() method:
public class Resolution {
    // your code here
    public String toString() {
        return String.valueOf(width) + "x" + String.valueOf(height);
    }
}

Or do this:
System.out.println(tv.getResolution().getWidth());
System.out.println(tv.getResolution().getHeight());

A: You should override toString() method in Resolution class.
You can take reference from here:-
See here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Responsive element height should equal width I have the following problem: I'm programing a game in javascript and I want it to be resposnive. The field of the game is a square wich contains 25 smaller squares.
Now I want that my site is responsive and the height of an square equals his width.
I tried to do this width the % property but that didn't worked.
Below you can see the class wich should have those properties.
.standart {

  display: flex;
    justify-content: center;
    align-items: center;
  font-size: 50px;
    width: 5.21%;
    height: 9.26%;
    background: blueviolet;
    border: 2px solid black;
 }

And here's the html code
<!DOCTYPE <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Level 1</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css">

Start

Restart

    Zum nächsten Level

 ←

→

↑

↓

X

Maybe someone knows how to help me.
Thanks

A: you can use vh and vw  instead of % .
VW: Viewport Width (vw) – A percentage of the full viewport width
Vh: Viewport Height (vh) – A percentage of the full viewport height


text:
Q: Get each Attribute of element in loop function I have a HTML DIV element:

I've a new Variable: attArray:
var attArray = new Array();

I want to get step by step each att in div.obj into attArray. How do I do it?
attArray[0] = "this is attr1"
attArray[1] = "this is attr2"
attArray[2] = "this is attr3"

A: Each element already has an attributes-collection, you can access it like an array.

A: Simple:
$('.obj').each(function() {
   var attArray = [];
   for(var k = 0; k < this.attributes.length; k++) {
       var attr = this.attributes[k];
       if(attr.name != 'class')
          attArray.push(attr.value);
   }
   //do something with attArray here...
});

Working example


text:
Q: Easy proof of Noether's theorem? I' looking for an easy proof of Noether's theorem? I mean I know that the variation must be
$ 0=\delta S = (EULER-LAGRANGE)+ (CONSERVED\, \, \, CURRENT) $
for the case of a particle $q(t)$. I know how to obtain it by I have doubts for the case of fields $ \phi (x) $, any hint? I have checked several books but I cannot find any easy proof of Noether's theorem anywhere; they use too complicated methods.

A: We consider infinitesimal transformations of a field in the form,
$$\phi\to\phi' = \phi(x)+\alpha \Delta \phi(x)$$
for an infinitesimal parameter $\alpha$. The system is said to be invariant under such a transformation if it changes up to a total derivative or surface term, i.e.
$$\mathcal{L}\to\mathcal{L}'=\mathcal{L}(x)+\alpha \,\partial_\mu F^{\mu}(x)$$
By varying with respect to the fields,
$$\alpha \Delta \mathcal{L} = \frac{\partial \mathcal{L}}{\partial \phi}\alpha \Delta \phi + \frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)}\partial_\mu (\alpha\Delta \phi)$$
$$= \alpha \underbrace{\partial_\mu \left( \frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)}\Delta \phi\right)}_{F^\mu(x)} + \alpha \left[ \frac{\partial \mathcal{L}}{\partial \phi}-\partial_\mu \left( \frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)}\right)\right]\Delta \phi$$
where in the last line we employed the equations of motion which arise by demanding $\delta S=0$. Notice the second term is zero for that reason, and hence we can declare,
$$j^{\mu}(x)=\frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)}\Delta \phi - F^{\mu}(x)$$
which satisfies the continuity equation, $\partial_\mu j^{\mu}=0$, or in vector calculus language,
$$\frac{\partial j^{0}}{\partial t}+\nabla \cdot \vec{j}=0$$
The corresponding Noether charge is given by,
$$Q=\int \mathrm{d}^{d-1} x \, j^{0}$$
which one can verify via the continuity equation and Stokes' theorem that $Q$ is conserved locally.

Useful Resources: Peskin and Schroeder's Introduction to Quantum Field Theory


text:
Q: PWA auto refresh / update client side on app update in Ionic 5 I have added the following code in my app.component.ts
constructor(private updates: SwUpdate,){

  {
    console.warn('check');
    this.updates.available.subscribe(event => {
        console.log('current version is', event.current);
        console.log('available version is', event.available);
        updates.activateUpdate().then(() => {
            console.warn('downloaded');
            document.location.reload();
        });
    });
    this.updates.activated.subscribe(event => {
        console.log('old version was', event.previous);
        console.log('new version is', event.current);
    });
}

I want to notify user when a new build is uploaded, and on clicking it, new build loads.
Do I need to write a service , store the version number in server and in local storage and keep checking for new version ?
Do I need to do anything else in app.component.ts ?
From where event.current, event.available values are coming ?
Edit 1
I don't see these messages in console even if I upload a new build
console.log('current version is', event.current);
console.log('available version is', event.available);

What is the reason for this?

A:
From where event.current, event.available values are coming ?

Not sure but I believe it depends on the file versioning, in case a new chunk is available on the server-side or where the application is hosted then it will trigger the new version or new update and get captured in the event script you wrote.

How you update on click

Firstly you need to be sure that a newer version is available to download, if so then you can hold the instance of new download in variable and call on click action (like the example provided in official documentation for ATHS - Add to home screen), like below -
let appUpdate = updates.activateUpdate();

PS: haven't tested this but have to post as an answer as the content is lengthy for comment.

A: Angular provides a way of checking if a new version available.
From the official docs:
@Injectable()
export class CheckForUpdateService {

  constructor(appRef: ApplicationRef, updates: SwUpdate) {
    // Allow the app to stabilize first, before starting polling for updates with `interval()`.
    const appIsStable$ = appRef.isStable.pipe(first(isStable => isStable === true));
    const everySixHours$ = interval(6 * 60 * 60 * 1000);
    const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);

    everySixHoursOnceAppIsStable$.subscribe(() => updates.checkForUpdate());
  }
}

What's happening under the hood is that Angular contacting your static files server (or CDN) trying to get a new ngsw file.
Once there is one, your available observable will emit, and will you can create any sort of UX you want making your users:
 constructor(updates: SwUpdate) {
    updates.available.subscribe(event => {
      if (confirm('New version is available, do you want to reload to update?')) {
        updates.activateUpdate().then(() => document.location.reload());
      }
    });
  }

You can replace this confirm with any other UX you like.


text:
Q: Postgresql - Query all time-series rows in a table SELECT * FROM table_1 ORDER BY time;

The above query will query all rows sitting in table_1, while sorting all the rows by a column time. However, if the size of the table gets millions of rows, fetching all rows in a table will be inefficient with the addition of ORDER BY time. However luckily, the table I have is a time-series table that uses TimescaleDB extension, and all rows are inserted in timely order.
In this case, what would be the most efficient way of fetching everything in a table, while ensuring the resulting query is ordered by time?
Do I just delete ORDER BY time? If I remove this, can I be sure that the resulting query will ALWAYS be in a order of time?
Also, I've heard that PostgreSQL has some driver issues when fetching all rows in a table, because its optimized for querying small fraction of data in a table. How can I optimize the performance?

A: There is no way to ensure the order of a dataset returned by a SELECT statement without using an explicit ORDER BY clause; this is true even if the data is stored within the table in an ordered manner. If you must have the data ordered, it is safest to define an ORDER BY clause.
Running a SELECT * against a TimescaleDB Hypertable isn't going to be efficient. TimescaleDB stores data in chunks within a hypertable, the idea being that you time-bound your query such that it hits a single specific chunk, which results in optimal performance. When you run a query that must hit all records in the table, it now has to look at all data contained within all of the chunks, and the only way to do this is via a sequential scan.
This leads to your question about PostgreSQL and fetching all rows. PostgreSQL leverages parallel sequential scans when a large portion of a table is going to be hit by a query. While this is going to yield better performance than a single-shot sequential scan, it's still not going to be as quick as index scan pulling a subset of data would be against the same table.
What is the reasoning behind needing to query all rows in the table? By virtue that any SQL engine would have to look at each row at least once in order to ensure that all rows are returned, there is no way that a SELECT * is ever going to be able to leverage the lookup advantages associated with hashing and indexing.


text:
Q: Invariant norms of tensors I am aware that certain special quantities of tensors (e.g. trace, det) are invariants (i.e. unchanging wrt coordinate system changes).
This wikipedia article says that the invariants of tensors are coefficients of the characteristic polynomial of the tensor. But are there not other ones?
In particular, are any of the standard matrix norms invariants?

A: So it seems like one way to do this is to use contractions as tensor norms, which are known to be invariant.
For instance, one can use the double contraction for many of the tensors from the continuum mechanics as a norm:
$$
   ||D|| = \sqrt{D:D} = \sqrt{\text{tr}\left(DD^T\right)}
$$
But, more generally (from here), one can use contractions. For instance, for a type (2,0)-tensor:
$$
 ||T||^2 = T_{ij} T^{ij}= g_{ik} g_{jl} T^{kl} T^{ij}
$$
Or, for a type-(1,3) tensor (e.g. the Riemann curvature tensor), one could do:
$$
   ||R||^2 = R_{ijk}^{l} R_{mno}^p g^{im} g^{jn} g^{ko} g_{lp}
           = R_{ijk}^l R_l^{ijk}
$$


text:
Q: Simplest 'true' value that the compiler doesn't recognise as true I had a little debug intercept that said
if (true)
    throw new Exception()
DoStuff();

However the compiler warned me that DoStuff() was unreachable code. So were the following:
if (1==1)
if (1 + 1 == 2)

The following 'works'
int x = 1;
if (2 * x == 2)
    throw...

What expression is obviously true to a human yet not to the compiler? The best I could manage was
bool False =>false;
if (False)

...and it has the wonderful property that to switch it off all I have to do is change it to
bool False=>true  /*  :D)     */

A: No need to mess up your code, you can do this:
[System.Diagnostics.Conditional("DEBUG")]
void stop() { throw new Exception(); }

To have a method which exists in Debug but doesn't exist in Release, used normally:
void MyMethod()
{
    stop(); // If you're in Release, this invocation will be removed
    DoStuff();
}

I do it all the time in my pieces of code, with my methods following the naming convention DebugConditional_CopyPasteOfContainerName()


text:
Q: Put ListView on CardView without the ListViews header My ListView has an header, with a lot of stuff in it. This stuff is arranged on two CardViews. Now there should be the rest of the ListView on a third CardView, but I dont see a way to achieve this.
When I simply put an CardView around the ListView, everything is on that CardView, but just the third part, the actual List, should be on that Card.
Anybody an Idea how to achieve this?


text:
Q: How to zip lists only if they of the same size and fail if their sizes differ? Suppose I am writing a function to zip two lists only if they are of the same size and fail otherwise:
 def foo(xs: List[Int], ys: List[Int]): Either[String, List[(Int, Int)]] =
    if (xs.size == ys.size) Right(xs zip ys) else Left(s"$xs and $ys have different sizes")

It works but I don't like using if. How would you improve the code above ?

A: You can use pattern matching if for some reason you don't like if
def zip(as: List[Int], bs: List[Int]): Either[String, List[(Int, Int)]] = (as, bs) match {
    case (Nil, Nil) => Right(Nil)
    case (a :: as1, b :: bs1) => for {
      t <- zip(as1, bs1)
    } yield (a, b) :: t
    case _ =>  Left(s"$as and $bs have different sizes")
  }

or
def zip(as: List[Int], bs: List[Int]): Either[String, List[(Int, Int)]] = {
    @tailrec
    def loop(as1: List[Int], bs1: List[Int], acc: List[(Int, Int)]): Either[String, List[(Int, Int)]] = (as1, bs1) match {
      case (Nil, Nil) => Right(acc)
      case (a :: as2, b :: bs2) => loop(as2, bs2, (a, b) :: acc)
      case _ => Left(s"$as and $bs have different sizes")
    }

    loop(as, bs, Nil).map(_.reverse)
  }


text:
Q: Authentication issues on Colab/Bigquery I use BigQuery from Colab for a long time, and since 2020 my account is on Google's enhanced security program. Until yesterday I had no issues authenticating with
from google.colab import auth
auth.authenticate_user()

Now, though, I get a 400 error. These are the details it gives:
access_type: offline
login_hint: (email)
response_type: none gsession
redirect_uri: https://colab.research.google.com/tun/m/auth-user-ephem
state: {"token":"(token)","endpoint":"(endpoint)","scopes":["openid","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/drive"]}
hd: (domain)
prompt: consent
client_id: (client_id)
scope: openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/drive

My question: are there configurations on the auth to allow for authenticating?

A: I've encountered this problem too. It seems that Google have changed the authentication procedure so that you (or your organisation) have to add colaboratory to the list of apps with permission to access your account.
However, there's also a way to revert to the old authentication behaviour which works without any special permissions:
import os
os.environ['USE_AUTH_EPHEM'] = '0'

from google.colab import auth
auth.authenticate_user()

If you look at the source code of the authenticate_user() function, you can see that it reads the USE_AUTH_EPHEM environment variable to decide whether to use the old or new authentication flow.
Update:
An alternative (and possibly more future-proof) way to authenticate is by running the following line in Colab.
!gcloud auth login --no-browser --update-adc

This requires you to have the Google Cloud CLI installed on your local machine, then just follow the instructions. If all goes well you'll be able to access BigQuery from within Colab without needing to call auth.authenticate_user() at all.

A: You may try the below alternative approach wherein you will upload your json key file (for authentication) in Google Drive, then mount it to Google Colab and then explicitly use it in your python code to authenticate your BigQuery API request.
from google.cloud import bigquery
from google.oauth2 import service_account
from google.colab import drive
import json
# Construct a BigQuery client object.

drive.mount('/content/drive/') # Mount to google drive

# Define full path from Google Drive.
# This example, the json key file is in /MyDrive/keys/
key_path = '/content/drive/MyDrive/keys/your-json-file.json'

credentials = service_account.Credentials.from_service_account_file(
    filename=key_path, scopes=["https://www.googleapis.com/auth/cloud-platform"],
)

client = bigquery.Client(credentials=credentials, project=credentials.project_id,)

query = """
    SELECT name, SUM(number) as total_people
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE state = 'TX'
    GROUP BY name, state
    ORDER BY total_people DESC
    LIMIT 20
"""

query_job = client.query(query)  # Make an API request.

print("The query data:")
for row in query_job:
    # Row values can be accessed by field name or index.
    print("name={}, count={}".format(row[0], row["total_people"]))

Below is the result of my above sample code when executed in Google Colab:


text:
Q: android pager sliding tabstrip fragment changer I want to change the layout by swyping over the tabs with fragments. Can anybody help me solve my problem?
Here is my fragmentactivity:
public class MainActivity extends FragmentActivity {

    private final Handler handler = new Handler();

    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    private MyPagerAdapter adapter;

    private Drawable oldBackground = null;
    private int currentColor = 0xFF666666;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        adapter = new MyPagerAdapter(getSupportFragmentManager());

        pager.setAdapter(adapter);

        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                .getDisplayMetrics());
        pager.setPageMargin(pageMargin);

        tabs.setViewPager(pager);

        changeColor(currentColor);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

        case R.id.action_contact:
            QuickContactFragment dialog = new QuickContactFragment();
            dialog.show(getSupportFragmentManager(), "QuickContactFragment");
            return true;

        }

        return super.onOptionsItemSelected(item);
    }

    private void changeColor(int newColor) {

        tabs.setIndicatorColor(newColor);

        // change ActionBar color just if an ActionBar is available
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            Drawable colorDrawable = new ColorDrawable(newColor);
            Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
            LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });

            if (oldBackground == null) {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    ld.setCallback(drawableCallback);
                } else {
                    getActionBar().setBackgroundDrawable(ld);
                }

            } else {

                TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });

                // workaround for broken ActionBarContainer drawable handling on
                // pre-API 17 builds
                // https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    td.setCallback(drawableCallback);
                } else {
                    getActionBar().setBackgroundDrawable(td);
                }

                td.startTransition(200);

            }

            oldBackground = ld;

            // http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler
            getActionBar().setDisplayShowTitleEnabled(false);
            getActionBar().setDisplayShowTitleEnabled(true);

        }

        currentColor = newColor;

    }

    public void onColorClicked(View v) {

        int color = Color.parseColor(v.getTag().toString());
        changeColor(color);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentColor", currentColor);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        currentColor = savedInstanceState.getInt("currentColor");
        changeColor(currentColor);
    }

    private Drawable.Callback drawableCallback = new Drawable.Callback() {
        @Override
        public void invalidateDrawable(Drawable who) {
            getActionBar().setBackgroundDrawable(who);
        }

        @Override
        public void scheduleDrawable(Drawable who, Runnable what, long when) {
            handler.postAtTime(what, when);
        }

        @Override
        public void unscheduleDrawable(Drawable who, Runnable what) {
            handler.removeCallbacks(what);
        }
    };

    public class MyPagerAdapter extends FragmentPagerAdapter {

        private final String[] TITLES = { "Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
                "Top New Free", "Trending" };

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {
            return SuperAwesomeCardFragment.newInstance(position);
        }

    }
}

And here is my fragment that writes the numbers of the positions in a text view:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;

public class SuperAwesomeCardFragment extends Fragment {

    private static final String ARG_POSITION = "position";

    private int position;

    public static SuperAwesomeCardFragment newInstance(int position) {
        SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        position = getArguments().getInt(ARG_POSITION);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        FrameLayout fl = new FrameLayout(getActivity());
        fl.setLayoutParams(params);

        final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
                .getDisplayMetrics());

        TextView v = new TextView(getActivity());
        params.setMargins(margin, margin, margin, margin);
        v.setLayoutParams(params);
        v.setLayoutParams(params);
        v.setGravity(Gravity.CENTER);
        v.setBackgroundResource(R.drawable.background_card);
        v.setText("CARD " + (position + 1));

        fl.addView(v);
        return fl;
    }
}

the library and the full code of the sample you can found here:
https://github.com/astuetz/PagerSlidingTabStrip

A: I know its late but might help someone:
Here is the quick fix:
Create other layouts first, let's assume that you create 3: I am also assuming the layout to give a clear idea
layout/lay1.xml - has a textview only
layout/lay2.xml - has an imageview only
layout/lay3.xml - has both textview and imageview

now inside oncreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // if else or switch case, your wish
    View view;
    if (position == 0) {
        // means lay1.xml
        view = inflater.inflate(R.layout.lay1, container, false);
        TextView tv = (TextView) view.findViewById(R.id.tv);
        tv.setText("Content not available");
        return view;

    } else if (position == 1) {
        // means lay2.xml
        view = inflater.inflate(R.layout.lay2, container, false);

        ImageView imagebg = (ImageView) view.findViewById(R.id.image1);

        imagebg.setImageResource(R.drawable.ic_launcher);
        return view;

    } else {
        // means lay3.xml
        view = inflater.inflate(R.layout.lay3, container, false);

        ImageView imagebg = (ImageView) view.findViewById(R.id.image1);
        imagebg.setImageResource(R.drawable.ic_launcher);

        TextView tv = (TextView) view.findViewById(R.id.tv);
        tv.setText("this is working wow, thanks.");

        return view;

    }
}


text:
Q: When does multiprocessing.BaseManager use RemoteError? I have a C extension module for CPython. I need multiple uWSGI workers to share a single instance of an object in this module. I am using a custom subclass of multiprocessing.BaseManager to accomplish this, based on this answer that describes a very similar solution.
The first script below is wifi.manager (wifi.controller.IFace is the object to be shared). I run this with python3 wifi/manager.py and then start the web server, which runs the code in the second snippet to get the shared object instance.
wifi/manager.py:
#!/usr/bin/env python3

from multiprocessing.managers import BaseManager

# .register() changes the class itself. We don't want to do that to BaseManager.
class WifiManager(BaseManager):
    pass

if __name__ == '__main__':
    # If we are executed as a script (python3 manager.py), start the server
    import atexit
    from multiprocessing import Lock
    import wifi.controller

    ifaces_lock = Lock()
    ifaces = dict()

    def get_iface(iface_path):
        with ifaces_lock:
            if iface_path not in ifaces:
                # Control interface isn't open. Open it.
                iface = wifi.controller.IFace(iface_path)
                ifaces[iface_path] = iface
        return ifaces[iface_path]

    def close_ifaces():
        for iface in ifaces.values():
            iface.close()

    WifiManager.register('get_iface', get_iface)
    atexit.register(close_ifaces)

    manager = WifiManager(address=('127.0.0.1', 2437), authkey=b'wifimanager')
    server = manager.get_server()
    server.serve_forever()
else:
    # If we are imported, provide the WifiManager class ready for clients to use
    WifiManager.register('get_iface')

Snippet from web application:
from wifi.manager import WifiManager

...

wmanager = WifiManager(address=('127.0.0.1', 2437), authkey=b'wifimanager')
wmanager.connect()
iface = wmanager.get_iface(iface_path)

iface.scan() # And other code using the iface object

The wifi.controller.IFace object sometimes raises exceptions, either built-in ones (mainly OSError) or its own wifi.controller.WifiError exception. Sometimes, I want to be able to catch these in the web app to present meaningful error pages to the client. But, what I've noticed is sometimes, these exceptions get captured and the same exception (e.g. WifiError) is raised in the web app. Other times, the web app gets a multiprocessing.managers.RemoteError with the traceback from the manager stored as a string.
The question is, how do I know when it will raise the original exception and when it will raise a RemoteError, so I know which one to catch? All the Python docs say is this:

If an exception is raised by the call, then is re-raised by _callmethod(). If some other exception is raised in the manager's process then this is converted into a RemoteError exception and is raised by _callmethod().

This isn't very clear to me and I can't figure out how it lines up with the behavior I've observed.

A: I believe I've figured it out. I'm still not 100% sure, but seeing as how this question isn't getting a lot of attention, I figured I'll go ahead and add an answer in case future readers stumble across this.
Exceptions that happen in the WifiManager during the original remote call get raised as RemoteError. In this case, that means exceptions on the remote end during this line in the web app:
iface = wmanager.get_iface(iface_path)

After that, the web app is no longer directly interacting with the WifiManager. It is only interacting with iface, a proxy object. If a proxy object (or more accurately, its referent) raises an exception on the remote side, the same exception gets raised in the web app, not a RemoteError. So, that means if this line were to cause e.g. a WifiError or OSError, those are the exceptions you would catch:
iface.scan() # And other code using the iface object

So, to summarize, calls on BaseManager (or subclasses) raise RemoteError when there is an exception on the remote end. Calls on proxy objects raise a copy of the original exception.
Bear in mind, this answer is based on my observations, not my complete and total understanding of the situation, so it's possible there are some gotchas here I'm unaware of. If somebody knows better, please correct me. But this describes the behavior I've observed and seems consistent with the docs quoted in the question.


text:
Q: Selenium WebDriverError on Rails 3.2 with cucumber I have a Rails 3.2 app. I am trying to set up cucumber tests to run using Google chrome. I have added config for the same:
Capybara.register_driver :selenium do |app|
  Capybara::Selenium::Driver.new(app, :browser => :chrome)
end

Also, I have installed the chromedriver with its binary in /usr/bin/  :
➜  ~  ls -lah /usr/bin | grep chrome
-rwxrwxrwx  1 root   root     18M May 20 15:42 chromedriver
lrwxrwxrwx  1 root   root      32 Apr  6 10:19 google-chrome -> /opt/google/chrome/google-chrome

When I try to run a simple feature which just opens google.com and searches something, I get the following error:
unexpected response, code=404, content-type=""
      unknown command: session/url (Selenium::WebDriver::Error::WebDriverError)
      ./features/step_definitions/google_steps.rb:2:in `/^I am on the google page$/'
      features/google.feature:3:in `Given I am on the google page'

Rest of the trace:
unexpected response, code=404, content-type=""
      unknown command: session/url (Selenium::WebDriver::Error::WebDriverError)
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/remote/http/common.rb:66:in `create_response'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/remote/http/default.rb:66:in `request'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/remote/bridge.rb:619:in `raw_execute'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/remote/bridge.rb:597:in `execute'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/remote/bridge.rb:103:in `get'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/selenium-webdriver-2.32.1/lib/selenium/webdriver/common/navigation.rb:14:in `to'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/capybara-2.1.0/lib/capybara/selenium/driver.rb:90:in `reset!'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/capybara-2.1.0/lib/capybara/session.rb:77:in `reset!'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/capybara-2.1.0/lib/capybara.rb:245:in `block in reset_sessions!'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/capybara-2.1.0/lib/capybara.rb:245:in `each'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/capybara-2.1.0/lib/capybara.rb:245:in `reset_sessions!'
      /home/arkiver/.rvm/gems/ruby-1.9.3-p392@tests/gems/capybara-2.1.0/lib/capybara/cucumber.rb:10:in `After'

Need help figuring out what am I missing here.

A: I fixed this problem. I was (accidently?) using the wrong driver version:
From https://code.google.com/p/chromedriver/downloads/list , I downloaded this version:
" chromedriver_linux64_26.0.1383.0.zip  ChromeDriver server for linux64 "
Instead of my previously selected:
"  chromedriver2_linux64_0.8.zip     version of ChromeDriver2 r195627   Release "
That fixed it.

A: I had the same problem.  In my case I had the latest driver, but I needed to update the selenium gem I was using to the latest version as well.


text:
Q: Apache-Mina FTPServer Issue -- Authentication Failed but used correct user/pass...? [Resolved] I finally got the Mina FTPServer up and running with the help of Femi (another user here).
so here's the issue:
I have the server setup for SQL based user management through db-user-manager on my Win2k3 server, and have two users set up in the table:
john // password
jim // password
Both of them are set to the following table properties:
userid      userpassword        homedirectory       enableflag      writepermission     idletime        uploadrate      downloadrate        maxloginnumber      maxloginperip
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
john        password            c:\pub\john         1               0                   30              1               NULL                5                   3
jim         password            c:\pub\jim          1               0                   30              1               NULL                5                   3

And when logging in to the FTP server using the CORRECT user//password combo of john//password, the log shows this:
RECEIVED: USER john
SELECT userid, userpassword, homedirectory, enableflag, writepermission, idletime, uploadrate, downloadrate, maxloginnumber, maxloginperip FROM FTP_USER WHERE userid = 'john'
RECEIVED: PASS *****
SELECT userpassword FROM FTP_USER WHERE userid = 'john'
USER FAILED TO LOG IN
Login Failure - john
SENT: 331 user name okay, need password for john.
SENT: 530 authentication failed.
CLOSED

I KNOW for a fact that I didn't screw up entering the username or password (because they are too easy to screw up...), and the fact that I get prompted for the username and password tells me that the host I entered is correct... so where else could I be screwing up at...?
Here is a link to my original post that Femi helped me out in. it contains the xml config file if needed:
https://stackoverflow.com/questions/6711542/apache-mina-ftpserver-database-user-manager-failure
Can someone PLEASE help me?

A: I noticed that in your xml code, for the user manager tag you only have
<db-user-manager>
in the documentation, it shows it as
<db-user-manager encrypt-passwords="salted">
I think this is where your problem lies. since the encryption isn't defined in your code, it defaults as MD5. change yours to one of the 3 below:
"Salted"
"MD5"
"Clear"
and you should be all set to go. Let me know if it works. The documentation is retarded and says "not required", but I call BS, since it automatically defaults to md5 if left out... so in a way it IS required if you're not using MD5 encryption on your passwords.


text:
Q: How can I use subprocess.run() in a detached process In a python script, I want to call subprocess.run() multiple times with varying arguments. While this initially works fine from the cli, it fails when the script is detached from the shell, eg with script.py &
As an example, lets transcode a folder of .wav files.
from glob import glob
import subprocess as sp

for w in sorted(glob('*.wav')):
    sp.run(['ffmpeg', '-y', '-i', w,
        '-f', 'mp4', '-vn', '-acodec', 'libfdk_aac',
        '-ac', '2', '-ab', '196k', f'{w}.m4a'],
        capture_output=True)

How can I get this script to run detached?

A: While I was unable to find a solution on the web, I did find an option to make this work, so I am documenting it here for others.
Enabling start_new_session was the solution for me, this is a Popen option that gets passed on in the underlying code.
from glob import glob
import subprocess as sp

for w in sorted(glob('*.wav')):
    sp.run(['ffmpeg', '-y', '-i', w,
        '-f', 'mp4', '-vn', '-acodec', 'libfdk_aac',
        '-ac', '2', '-ab', '196k', f'{w}.m4a'],
        capture_output=True, start_new_session=True)


text:
Q: Internal Server Error when uploading video I get INTERNAL SERVER ERROR when trying to upload a file that is larger than ~15 MB.
It happens on many Typo3 installations.
I have set post_max_size and upload_max_filesize to 100 megabytes.
max_execution_time and max_input_time to 1000.
Typo3 6.2 and 7.6.

A: You have also to look at the max execution time and max input time of php.
max_execution_time = value_in_seconds
max_input_time = value_in_seconds

If this is not helping, look at your apache error log file which error is displayed.

A: Other possible problems:

*

*Does the filename contain characters that are not compatible with your system?

*Is the user (you) allowed to upload to the upload directory?

*Are the permissions for the target folder correctly set (see Installtool -> Folder Structure)


text:
Q: How to use WITH Clause in BULK COLLECET inside plsql I want to know how to use WITH Clause in BULK COLLECT inside PL/SQL block.
Presently I am able to get the data into collection variable as below.
set serveroutput on;
declare
    type row_data is table of varchar2(256) ;
    row_d row_data;
begin
    select some_column bulk collect into row_d from some_table;
    dbms_output.put_line(row_d(1));
end;

But I need to get the data from different tables. For this I am using with clause as mentioned below.
with diff_tab_data as
(
select some_column from some_table1;
union all
select some_column from some_table2;
union all
select some_column from some_table3;
union all
select some_column from some_table4;
union all
select some_column from some_table5;
);
select some_column from diff_tab_data;

How to use the above query with bulk collect . I have already tried the same as below but I am getting the error
set serveroutput on;
declare
    type row_data is table of varchar2(256) ;
    row_d row_data;
begin
    with diff_tab_data as
    (
    select some_column from some_table1
    union all
    select some_column from some_table2
    union all
    select some_column from some_table3
    union all
    select some_column from some_table4
    union all
    select some_column from some_table5
    );
    select some_column into bulk collect row_d from diff_tab_data;
    dbms_output.put_line(row_d(1));
end;

Request you to help in this

A: Example based on Scott's sample tables:
SQL> DECLARE
  2     TYPE row_data IS TABLE OF VARCHAR2 (256);
  3
  4     row_d  row_data;
  5  BEGIN
  6     WITH
  7        diff_tab_data (col)
  8        AS
  9           (SELECT dname FROM dept
 10            UNION ALL
 11            SELECT ename FROM emp
 12            UNION ALL
 13            SELECT loc FROM dept
 14            UNION ALL
 15            SELECT job FROM emp
 16            UNION ALL
 17            SELECT dummy FROM DUAL)
 18     SELECT col
 19       BULK COLLECT INTO row_d
 20       FROM diff_tab_data;
 21
 22     DBMS_OUTPUT.put_line (row_d (1));
 23  END;
 24  /
ACCOUNTING

PL/SQL procedure successfully completed.

SQL>

As you can see, each select in with factoring clause does not end with a statement terminator. The rest of it, you did mostly OK (missing bulk collect).


text:
Q: What does this mean (function($) {} if I write this code:
(function($){})

Does it mean that in this function I can write instead of word "function" just "$".
Thank you for explaining this.

A: No. What it means is that $ can be used with a particular meaning inside of that context. This sort of thing is frequently used when variables like $ are used by two or more toolkits. For example, jQuery often is written like this to handle a document-ready method:
jQuery(function($) {
    $('#div').something()...
});

That way, you can be sure that $ will mean jQuery in that context even if you called jQuery.noConflict elsewhere.
This particular syntax, (function($){}) is typically done like this:
(function($){

})(jQuery);

That is done to create an anonymous function and call it with a particular context. Often it's used to do something like pass a particular iteration of a loop to an AJAX operation (like if you want to make 5 ajax calls inside of a loop that runs five times). Example:
for (var x = 0; x < 5; x++) {
    (function(index) {
        $.ajax(url, { data... }, success(data) {
            if (data.y == index)....
        });
    })(x);
}

A: It is an anonymous function , taking $ as an argument to use it in local scope.
It can be called like this :
(function($){ SOME_OPERATIONS_WITH_$ ;})(theObjectBeingPassedAsDollar)
eg. jQuery object can be passed to this instance, and it would be used in the anonymous function as $
This will alert HelloWorld :
(function($){ alert($.one + $.two); })( {'one':'Hello','two':'World'} )

demo:http://jsfiddle.net/Pg9s4/


text:
Q: Concurrency and SharePoint - Sequence Number Generation I have a dev question related to concurrency. Here's the problem:
I need to generate a sequential reference number for each document uploaded to a specific document library. The numbers basicaly look like this:
DocumentFooX12 - Sequence Number: 2014-0001
DocumentWhatever2a - Sequence Number: 2014-0002
Now this typically is not difficult to do with an Event Receiver and I have no problem writing the code. The problem though is related to concurrency.
We have a multi server farm and use Network Load Balancing. Whenever two people work at the same time, they might be working on different servers. I cannot guarantee that the numbers will really be sequential.I've tried a Lock Object in my event receiver but that doesn't make a difference because it only locks the thread on Server1, but not server 2.
Has anyone done some work with the State Service that might help me?
I've also tried a Timer Job, but the requirement dictates that the sequence number is generated almost immediately.

A: Have you looked at Flake ? I imagine distributed sequential ID generation to be a very complex subject. I'm almost sure you won't get an implementation that is robust and returns perfectly sequential id's. In Flake's case, client's can generate the ID's themselves but they use timeslots / ranges, so they are not perfectly sequential (e.g. the number will jump from 101 to 105 instead of 102):

*

*Id is composed of:

*

*time - 41 bits (millisecond precision)

*configured instance id - 10 bits - gives us up to 1024 instances

*sequence number - 12 bits - usually 0, incremented when more than one id is requested in the same millisecond and reset to 0 when the clock ticks forward. Rolls over every 4096 per machine.

*

*The generator has protection mechanism for sequence roll over in the same millisecond.

Good luck!
You may find more information when you look outside of a SharePoint implementation, especially when you need a distributed implementation.

A: Can you give us a little more details about the implementation?
How are you generating the sequential number and what exactly did you lock?


text:
Q: Is it possible to shrink rt.jar with ProGuard? Is there a procedure by which you can optimize/shrink/select/obfuscate only 'used by your app' classes/methods/fields from rt.jar provided by Sun by using some optimization software like ProGuard (or maybe other?). Then you would actually be able to minimize the download size of your application considerably and make it much more secure ? Right?
Related questions:

*

*Do you know if Sun's "jigsaw project" which is waited to come out, is intended to automatically handle this particular issue?

*Did somebody manage yet to form an opinion about Avian java alternative? Please share it here.

Thank you.

A: From the ProGuard Website:

the run-time classes from Sun's Java 6
Original size: 53 M
After shrinking: 23 M
After optim.: 22 M
After obfusc.: 18 M
Total reduction: 66 %

I've just recently seen apps Pack200, which seems to be something you might be interested in.
Project Jigsaw will modularize Java/the JRE (7), so that only modules needed are loaded.

A: The Sun/Oracle JRE Binary License does not permit subsetting the Java Runtime, or fiddling with rt.jar. There are a few optional files that you may remove when bundling the JRE with your app, but that won't make much difference.
So wait for JDK 7 or explore a Sun-approved way to reduce the download size of your Java app.


text:
Q: how to store 2d array in pandas df and read it without it turning into strings I have a df where a column is array where each cell is 1*50 dimension and there are 20 rows.
import pandas as pd
df = pd.DataFrame(zip(list(range(0, 20, 1)), np.random.rand(20, 50)),
             columns=['id', 'array'])

At this point there is no issue to use the array column for any array operations (addition, multiplication, division etc) with other array.
But if one saves the df as csv and reads it in another notebook (which I don't have a good way to demo here), each cell in the array column turns into list wrapped strings and using either ast literal_eval or to_numpy doesn't help.
'[1.2 -2.3 2.1 ... 4.1]'

How to prevent array turning into strings here?

A: For me the usage of converters in pandas.read_csv works. The converters get a lambda function, which strips each string, and removes the linebreaks. Afterwards, I can apply np.fromstring with space as seperator.
pd.read_csv("file.csv",converters={"array":lambda x: np.fromstring(x.strip("][").replace("\n", ""), sep=" ")})


text:
Q: How to invoke Azure Function on User Defined Schedules I've an HTTP triggered azure function (Java) that performs a series of action. In tmy application UI, I've a button which triggers this function to initiate the task.
Everything works as expected.
Now I've to perform this operation in user defined schedules. That is from the UI, user can specify the interval (say every 3 Hrs) at which the function need to be executed. As this schedule will be custom and dynamic I cannot rely on the timer-triggered azure functions. Also the same function need to be executed at different intervals with different input parameters.
How can I dynamically create schedules and invoke the azure function on the scheduled time? Does Azure have an option to run the function with specific events something like (AWS cloud watch rule + lambda invocation)?
EDIT: Its different from the suggested question as it changes the schedule of an existing function.And I think configuring a new schedule will break the previously configured schedules for the function. I want to run the same function in different schedules as per the user configuration and should not break any of the previous schedules set for the function.

A: You can have a try to modify the function.json, change the cron expression in function.json. Please refer to the steps below:

*

*Use Kudu API to change function.json https://github.com/projectkudu/kudu/wiki/REST-API
PUT https://{functionAppName}.scm.azurewebsites.net/api/vfs/{pathToFunction.json}, Headers: If-Match: "*", Body: new function.json content.

*Then send request to apply changes.
POST https://{functionAppName}.scm.azurewebsites.net/api/functions/synctriggers

A: You can use a durable function for this, applying the Monitor Pattern (shamelessly copied from this MSDN documentation).
This orchestration function sets a dynamic timer trigger using context.CreateTimer.
Code is in C#, but hopefully there is something you can use here.
[FunctionName("MonitorJobStatus")]
public static async Task Run(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    int jobId = GetJobId();
    int pollingInterval = context.GetInput<int>();
    DateTime expiryTime = GetExpiryTime();

    while (context.CurrentUtcDateTime < expiryTime)
    {
        var jobStatus = await context.CallActivityAsync<string>("GetJobStatus", jobId);
        if (jobStatus == "Completed")
        {
            // Perform an action when a condition is met.
            await context.CallActivityAsync("SendAlert", machineId);
            break;
        }

        // Orchestration sleeps until this time.
        var nextCheck = context.CurrentUtcDateTime.AddSeconds(pollingInterval);
        await context.CreateTimer(nextCheck, CancellationToken.None);
    }

    // Perform more work here, or let the orchestration end.
}


text:
Q: Need to Replicate dict data inside array json_data = {"map":[{"name":"test"}]}

def replicator(data, replica=1):
    final_data = {}
    for each_map_tcs in data.keys():
        for each_tc in data[each_map_tcs]:
            for i in range(replica):
                if each_map_tcs not in final_data.keys():
                    final_data[each_map_tcs] = []

                final_data[each_map_tcs].append(each_tc)
                each_tc['name'] += '-' + str(i)

    print(final_data)

replicator(json_data, 2)

Actual output:
{'map': [{'name': 'test-01'}, {'name': 'test-01'}]}
Required output :
{'map': [{'name': 'test-0'}, {'name': 'test-1'}]}

A: it looks like you just want to create a list-of-dicts to be the value of the larger dict.
the list part can be created with list comprehension which you can then incorporate into the dict like this:
l = [{'name': 'test-0' + str(x)} for x in range(2)]
d = {'map':l}
print(d)

result:
{'map': [{'name': 'test-00'}, {'name': 'test-01'}]}

A: import copy

json_data = {"map":[{"name":"test"}]}

def replicator(data, replica=1):
    final_data = {}
    for each_map_tcs in data.keys():
        for each_tc in data[each_map_tcs]:
            for i in range(replica):
                if each_map_tcs not in final_data.keys():
                    final_data[each_map_tcs] = []

                tmp_dict = copy.deepcopy(each_tc)
                tmp_dict['name'] += '-' + str(i)
                final_data[each_map_tcs].append(tmp_dict)

    print(final_data)

replicator(json_data, 2)


text:
Q: Switching mobile app traffic from http to https I have a mobile app that communicate with ubuntu (AWS) production server over http.
We now would like to switch traffic over https and our apps on the stores are hard coded with the domain on http. Now we are about to release an updated set of app with the same domain hardcoded as https.
The issue is now with users who have already using the old app once we make changes live the will no longer be able to communicated with the server on https (the server is forced to listed to port 443). On the other hand users who are going to download the new app will be might be also not being able to communicate with the server in during the time we switch the traffic to https.
My question:

Is there any way we can have both traffic enabled so both
  users of the old and the new app can communicate with the server
  before and after the change to https?

Thank you in advance!

A: This is what you need to do
Redirect http to https
You can check this link as well
Apache Rewrite Http to Https


text:
Q: Regular expression to Allow 1st character as Alphabet and then numbers only I want a regular expression to allow first character be an alphabet and
then numbers only with following constraints :

-no space
-no special characters

like AS2, Nf2, nf_2, nf 08 should not be allowed.
'N00044,n0,n09,n099,123456,123'  allowed

A: You can try this regex :
^[A-z]\d+$

if you want a minimum of 1 digit necessary, or
^[A-z]\d*$

if having a digit is not mandatory.

A: Jarvis's does meet the requirement but you can also use numeric range for the same since \d is specifically used for ASCII numbers.  Refer when to use \d and [0-9].
Since numbers are required to be matched in your regex I would prefer as follows:
 ^([A-z][0-9]+)$

Regex101- test cases
As per your requirement in comments, following regex should do the work for you:
^(([A-z][0-9]+)|([0-9]+))$

Regex101- New test cases
It will match an input with alphabet followed by numbers or an input with only numbers.


text:
Q: Need to add total to union query that already has count My problem has me stumped and I don't know where to educate myself on this challenge.
I have a bunch of kid's ages I'm counting up from data in a family event registration db built in php and mysql. The kids are registering themselves and declaring the tribe group and their age they belong to. There are multiple events scheduled for registration at any given time. At any time, the event hosts need to see the age counts.  The total count of kids in each column works in a mysql window but not in html.  The mysql results so far look like this:
custom  item_number1    Age 7   Age 8  ....
703198  Apache            1     NULL
703198  Arapahoe          2     5
703198  Aztec             1     NULL
703198  Blackfoot         1     5
703198  Cherokee          1     1
703198  Chippewa          1     1
703198  Creek             1     2
703198  Fox               1     1
703198  Iroquois          1     NULL
703198  Mohawk          NULL    4
703198  Pawnee            1     2
703198  Yellowknives      2     1
703198  All Tribes        13    22

Here's the code:
<?php
$query = "SELECT 703198 AS custom, item_name1
     , COALESCE(item_number1,'All Tribes') AS item_number1
     , COUNT(CASE WHEN Ages = 4 THEN 4 ELSE NULL END) AS 'Age 4'
     , COUNT(CASE WHEN Ages = 5 THEN 5 ELSE NULL END) AS 'Age 5'
     , COUNT(CASE WHEN Ages = 6 THEN 6 ELSE NULL END) AS 'Age 6'
     , COUNT(CASE WHEN Ages = 7 THEN 7 ELSE NULL END) AS 'Age 7'
     , COUNT(CASE WHEN Ages = 8 THEN 8 ELSE NULL END) AS 'Age 8'
     , COUNT(CASE WHEN Ages = 9 THEN 9 ELSE NULL END) AS 'Age 9'
     , COUNT(CASE WHEN Ages = 10 THEN 10 ELSE NULL END) AS 'Age 10'
     , COUNT(CASE WHEN Ages = 11 THEN 11 ELSE NULL END) AS 'Age 11'
     , COUNT(CASE WHEN Ages = 12 THEN 12 ELSE NULL END) AS 'Age 12'
     , COUNT(CASE WHEN Ages = 13 THEN 13 ELSE NULL END) AS 'Age 13'
     , COUNT(CASE WHEN Ages = 14 THEN 14 ELSE NULL END) AS 'Age 14'
     , COUNT(CASE WHEN Ages = 15 THEN 15 ELSE NULL END) AS 'Age 15'
     , COUNT(CASE WHEN Ages = 16 THEN 16 ELSE NULL END) AS 'Age 16'
     , COUNT(CASE WHEN Ages = 17 THEN 17 ELSE NULL END) AS 'Age 17'
   FROM ( SELECT item_number1
              , item_name1
              , item_name3 AS Item
              , item_number3 AS Ages
           FROM tbl_pp_transactions
          WHERE custom = 703198
            AND item_name3 = 'Daughter'
            AND item_number3 IN (4,5,6,7,8,9,10,11,12,13,14,15,16,17)
         UNION ALL
         SELECT item_number1
              , item_name1
              , item_name4 AS Item
              , item_number4 AS Ages
           FROM tbl_pp_transactions
          WHERE custom = 703198
            AND item_name4 = 'Daughter'
            AND item_number4 IN (4,5,6,7,8,9,10,11,12,13,14,15,16,17)
         UNION ALL
         SELECT item_number1
              , item_name1
              , item_name5 AS Item
              , item_number5 AS Ages
           FROM tbl_pp_transactions
          WHERE custom = 703198
            AND item_name5 = 'Daughter'
            AND item_number5 IN (4,5,6,7,8,9,10,11,12,13,14,15,16,17)
         UNION ALL
         SELECT item_number1
              , item_name1
              , item_name6 AS Item
              , item_number6 AS Ages
           FROM tbl_pp_transactions
          WHERE custom = 703198
            AND item_name6 = 'Daughter'
            AND item_number6 IN (4,5,6,7,8,9,10,11,12,13,14,15,16,17)
       ) AS dt
GROUP
    BY item_number1 WITH ROLLUP";
?>

I plan to shorten this up with a do/while loop once it works.  I'd like to get this into html using a prepared>statement approach.  But I don't think my binding names are correct.  Here's what I have:
<?php
if ($stmt = $con->prepare($query)) {
    $stmt->execute();
    $stmt->bind_result($custom, $item_name1, $item_number1, $Ages, $Item, $Item1, $Item3, $Item5, $Item7, $Item9, $Item11, $Item13, $Item15, $Item17, $Item19, $Item21, $Item23, $Item25);
?>

                            Tribe
                            Age 4
                            Age 5
                            Age 6
                            Age 7
                            Age 8
                            Age 9
                            Age 10
                            Age 11
                            Age 12
                            Age 13
                            Age 14
                            Age 15
                            Age 16
                            Age 17

                        <?php
                            while ($stmt->fetch()) {
                                echo "
";
                                printf("
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                %s
                                ", $item_number1, $Ages, $Item, $Item1, $Item3, $Item5, $Item7, $Item9, $Item11, $Item13, $Item15, $Item17, $Item19, $Item21, $Item23, $Item25);
                                echo "
";

                            }
                            $stmt->close();
                        }
                        ?>

Any suggestions or direction would be great?
Thanks

A: Here's the final answer.  The labels needed to be changes from $Item to $Ages
$stmt->bind_result($custom, $item_name1, $item_number1, $Ages, $Ages1, $Ages3, $Ages5, $Ages7, $Ages9, $Ages10, $Ages13, $Ages15, $Ages17, $Ages19, $Ages21, $Ages23, $Ages25);

", $item_number1, $Ages, $Ages1, $Ages3, $Ages5, $Ages7, $Ages9, $Ages10, $Ages13, $Ages15, $Ages17, $Ages19, $Ages21, $Ages23, $Ages25);


text:
Q: Implementing microphone analysis with Audiokit v5 I need to run my app which uses AudioKit as one of its libraries in Xcode 12 so I can prepare it for the upcoming iOS 14 release, since Xcode 12 contains all the changes to classes that need to be adopted by me.
However the current stable release of 4.10.1 does not compile in Xcode 12. I then tried to install the latest v5-develop version 5.0.b1 and that compiles successfully, however the API went through significant changes -> AudioKit.output for example is deprecated. I was unable to find any documentation regarding these changes. I reckon that is because it is still in beta.
I previously used this code I have taken from their microphone analysis example:
func setup(completion: @escaping TaskHandler) {
    // Setup the microphone
    AKSettings.audioInputEnabled = true
    mic = AKMicrophone()
    tracker = AKFrequencyTracker(mic)
    silence = AKBooster(tracker, gain: 0)

    // Start the audio engine
    AudioKit.output = silence
    do {
        try AudioKit.start()
        completion(true, nil)
    } catch {
        completion(false, ErrorMessage.microphoneFailedToStart)
        AKLog("AudioKit did not start!")
    }
}

and then I access the amplitude and frequency like this:
timer?.setEventHandler(handler: {
        let currentAmp = self.tracker.amplitude
        let currentFreq = self.tracker.frequency
        // ... some processing here
}

In the new version I dug around in Xcode and found and tried to get AKMicrophoneTrackerEngine to work and I got it to compile and run:
let engine = AKMicrophoneTrackerEngine()

func setup(completion: @escaping TaskHandler) {
    engine.start()
    completion(true, nil)
}

// ..later in code

timer?.setEventHandler(handler: {
        let currentAmp = self.engine.amplitude
        let currentFreq = self.engine.frequency
        // ... some processing here
}

However the frequency (and possibly amplitude) are slightly off. Playing a 1000Hz test tone using 4.10.1 produced exactly 1000 as an output but my new approach produces a value around 918.
Can anyone guide me to a piece of documentation or advise me how to implement the same functionality using the new API?
Thank you.

A: https://github.com/AudioKit/AudioKit/issues/2267 the issue should be fixed by updating to AudioKit 4.11.1 pod 'AudioKit' , '~> 4.11.1' . This version successfully compiles in Xcode 12. You also need to replace all AudioKit instances with AKManager for example: AudioKit.output = ... with AKManager.output = ...


text:
Q: Confluent Cloud Kafka - Audit Log Cluster : Sink Connector For Kafka cluster hosted in Confluent Cloud, there is an Audit Log cluster that gets created. It seems to be possible to hook a Sink connector to this cluster and drain the events out from "confluent-audit-log-events" topic.
However, I am running into the below error when I run the connector to do the same.
org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [connect-offsets]

In my connect-distributed.properties file, I have the settings as :
offset.storage.topic=connect-offsets
offset.storage.replication.factor=3
offset.storage.partitions=3

What extra permission/s needs to be granted so that the connector can create the required topics in the cluster? The key/secret being used in the connect-distributed.properties files is a valid key/secret that is associated to the service account for this cluster.
Also, when I run the consumer in the console using the same key (as above) , I am able to read the audit log events just fine.

A: It's confirmed that this feature (hooking up a connector to the Audit Log cluster) is not supported at the moment in Confluent Cloud.  This feature may be available later this year at some point.


text:
Q: soap core 6 service endpoint configuration I wrote a soap web service with .NET core 6 and published it on server A and I have a gateway whose address is server B. The gateway is Ocelot technology. Now I want to call this soap web service with c#. I expect that my "endpoint address" is the gateway address (server B), but server A address is created in the endpoint address
I want to set endpoint address="Server B which is the gateway
enter image description here


text:
Q: Protractor - Returning pending promise when functioned out I am trying to create a function that will comb through an array of elements and return the first instance of one that meets the criteria.
This is what I have inside my test that does work:
element.all(by.css('_cssSelector_')).filter(function(elms, index) {
        return elms.getAttribute('height').then(function(height) {
            return parseInt(height) > 0;
        });
    }).then(function(validElms) {
         browser.actions().mouseMove(validElms[0]).perform();
    }

...but if I function this out, it does NOT work:
getValidElm = function() {
    var validElm = element.all(by.css('_cssSelector_')).filter(function (elms, index) {
        return elms.getAttribute('height').then(function (height) {
            return parseInt(height) > 0;
        });
    }).then(function (validElms) {
        return validElms[0];
        });

    return validElm;
}

If I then run:
var validElmFromPage = getValidElm();
console.log(validElmFromPage);

I get: Promise::2046 {[[PromiseStatus]]: "pending"}
Which points to an issue of something inside the function not resolving before the var outside the function is being used. After reading (extensively) through posts here, and even this wonderful blog post (http://spin.atomicobject.com/2014/12/17/asynchronous-testing-protractor-angular/), I still can't figure out what the deal is. I know it's something simple, most likely controlFlow related?
Thanks for your help.

A: Let the function return a promise. Since filter() returns an ElementArrayFinder, you should be able to use first():
getValidElm = function() {
    return element.all(by.css('_cssSelector_')).filter(function (elms, index) {
        return elms.getAttribute('height').then(function (height) {
            return parseInt(height) > 0;
        });
    }).first();
}

first() would return an ElementFinder which you can pass to mouseMove():
var elm = getValidElm();
browser.actions().mouseMove(elm).perform();


text:
Q: Issue with c++ time function. So I am using function to get the time from time with an offset of 555550 which should give a value of 10:19:09. But when I use gmtime and asctime I get a value of 10 seconds instead of 9 seconds, and I don't understand why I am one second off. Could anyone please explain this?
Here is the code I am testing:
#include <stdio.h>
#include <time.h>

int main (void)
{
    time_t now = 555550;
    printf ("The time is %s", asctime (localtime (&now)));
    printf ("UTC time is %s", asctime (gmtime (&now)));
    return 0;
}

A: your calculation is wrong: see http://www.epochconverter.com/. 10 seconds is correct. How would a number divisible by 10 end up as 9 when modded by 60?

A: according to http://www.epochconverter.com/ the value of 555550 is Wed, 07 Jan 1970 10:19:10 GMT, so your assumption about 555550 to be 10:19:09 was wrong.


text:
Q: What is the information called below a data table? I can't think very well these days, and I can't figure this out.
I have a table I'm using for a web page. I have some footer information, and text from the superscript in the table, data sources, notes, etc. It's not a simple caption, but actually explanations of the data. I'm either going to have it like an expanding link, or have a modal popup come up and give that info.
My question is: what should that link be called? What is the grouping of information regarding the data in a table?
thanks.


text:
Q: TYPO3 9.5 Tutorial needed It might be a bit too general, but I need a reasonable tutorial on TYPO3 9.5
I just finished going through the tutorials on TYPO3 site, but to my frustration they are all but useless when it comes to simplest of questions.
For example:
After creating a template, how do I assign content to the correct parts of the page?
And a dozen or so more of the ilk.
Some reasonable introduction to extensions in TYPO3 would be nice as well.
Honestly if it were not for the customer, I could of done 3 or four similar sites in the time it takes to work how TYPO3 works :-(

A: I had my start with TYPO3 using Wolgang Wagners video tutorials. It costs 77 Euros, is in German language and only available for version 7 and 8. Most of it should still be applicable to version 9.

A: As per FrankHsnblg suggestion feel free to check it out.
The guy Frank advised has a nice tutorial on his Youtube channel that should get most of the people started.
I could understand it even with some rather basic German knowledge
https://www.youtube.com/watch?v=H5-zqudJz0o

A: If you know German, I suggest to you these tutorials.
Daniel macht TYPO3
Even tho Daniel is using version 7.6, you will learn a lot.
Have fun :)


text:
Q: How to get column and row from partial string in pandas dataframe efficenitly How to get column row and value from partial string efficiently with Pandas
I have a pandas dataframe setup with about 150 indexes and 8 columns what I am looking to do is efficiently get the the
column and index for cells based on a partial string. What I came up with was as follows:
df = pd.DataFrame([["foo", "foo", "foo", "foo"], ["foo", "bar", "foo", "foo"], ["bar", "foo", "foo", "bar"],
                   ["foo", "foo", "foo", "bar"]])

Output:
 0    1    2    3
 0  foo  foo  foo  foo
 1  foo  bar  foo  foo
 2  bar  foo  foo  bar
 3  foo  foo  foo  bar

Here if I'm looking for just the entries that contain the sub-string "ar" I employ:
setup_mask = df.applymap(lambda x: "ar" in str(x))
values_hold = []
for x in df.index:
    for y in df.columns:
        if setup_mask.loc[x, y].any() == bool(True):
            if [x, y] not in values_hold:
                values_hold.append([x, y])

This works well and returns a list of index column values
[[1, 1], [2, 0], [2, 3], [3, 3]].
This feels unpythonic and really just plain messy is there a way to do something like this in a more pythonic way?
P.S. I know I could cut out the mask but I felt like if there is a more pythonic way it would rely on a mask.

A: Pandas supports vectorized string operations, but only on one column at a time.  So:
df.apply(lambda ser: ser.str.contains('ar'))

Will give you this:
       0      1      2      3
0  False  False  False  False
1  False   True  False  False
2   True  False  False   True
3  False  False  False   True

And it's pretty efficient so long as you have fewer columns than rows (which you do).
If you store the above in mask, then:
np.transpose(np.where(mask))

Gives you your answer:
array([[1, 1],
       [2, 0],
       [2, 3],
       [3, 3]])

A: You can use transform with str.contains and stack
In [5352]: s = df.transform(lambda x: x.str.contains('ar')).stack()

In [5353]: s.index[s].tolist()
Out[5353]: [(1L, 1L), (2L, 0L), (2L, 3L), (3L, 3L)]

Or, as list of lists
In [5366]: [list(map(int, x)) for x in s.index[s]]
Out[5366]: [[1, 1], [2, 0], [2, 3], [3, 3]]


text:
Q: How to make font size in textarea same as input field in CSS? The font size in the textarea in https://jsfiddle.net/Ljxwre2y/ is smaller than in the input field, how can I make them both the same size?
body {
  font-family: 'Montserrat';
  font-size: 30px;
}

input,textarea {
  margin: 0;
  padding: 0;
  width: 100%;
}

textarea {
  font-family: inherit;
}

A: add font-size in both input, textarea
input,textarea{
font-size: 30px;
}

A: This is what I usually do, always works for me.
in your body tag, specify font-family
and others... like font-size.
html,
body {
    height: 100%;
    font-family: 'Source Sans Pro', monospace;
}

then, inherit...
textarea,
input,
select {
    font-size: inherit;
    font-weight: inherit;
    text-decoration: none;
    font-family: inherit;
    color: #19272D; /*your input color*/
}

A: You have to explicitly set them in CSS to prevent the browser from using the browser defaults. Like this:
input, textarea {font-size: 14px;}

See jsfiddle
input, textarea {font-size: 14px; font-family: sans-serif;}

Use the above code to make the fonts exactly the same (so not only the size). See jsfiddle

A: Try this:
input, textarea {
    margin: 0;
    padding: 0;
    width: 100%;
    font-family: "Monsterrat";
    font-size: 30px;
}

Both input and textarea doesn't inherit font family. So you need to set font-family property to either your font name or inherit keyword.

A: You can use the '*' selector to set fonts, size and Family, then it will apply to all elements on the page, like this:
*
{
    font-size: 14px;
    font-Family: Arial;
}

Add this as the first entry in your css.


text:
Q: Saving full array as txt in python I at the moment trying to sample an audio files and store the information from the sampling into to txt file.
The sampling is done using the librosa.
The problem occurs when i save  it to a file...
The array doesn't get fully saved, I am only able to view a few of the sampling point, and the rest is dotted.
example:
22050.000
[ -8.61534572e-05  -1.64340396e-04  -8.03423245e-05 ...,  -1.40137578e-04
  -3.71412549e-04  -5.04361582e-04]

This is how i am doing it:
import tensorflow as tf
import numpy as np
import librosa
from os import listdir
from os.path import isfile, join
import os

path_train =  "/home/k/kaldi-trunk/egs/start/s5/data/train"
path_test =  "/home/k/kaldi-trunk/egs/start/s5/data/test"
dnn_train = "/home/k/kaldi-trunk/dnn/train/"
dnn_test = "/home/k/kaldi-trunk/dnn/test/"
dnn = "/home/k/kaldi-trunk/dnn/"
path  = "/home/k/kaldi-trunk/egs/start/s5/data/"
train_filelist = path_train+"/wav_train.txt"
test_filelist = path_test+"/wav_test.txt"

    files_train = [f for f in listdir(dnn_train) if isfile(join(dnn_train, f))]
    files_test = [f for f in listdir(dnn_test) if isfile(join(dnn_test, f))]

    os.chdir(dnn_train)
    train = []
    test  = []

    for line in files_train:
        #print dnn_train+line
        y,sr=librosa.core.load(dnn_train+line)
        train.append(y.tolist())

    print "Train done!"

    for line in files_test:
        x,sr=librosa.core.load(dnn_test+line)
        test.append(x.tolist())

    print "Test done!"

    os.chdir(dnn)

    with open('sample_test.txt','wb') as f:
        np.savetxt(f,test)

    with open('sample_train.txt','wb') as f:
        np.savetxt(f,train)

anything that could explain why i can't save all the sample point rather than a few?
desired output is two seperate files [sample_test,sample_train]
in which each line contain a list.
each entry in the list should contain as many decimals, which is why either it would be appreciated having it stored as either float or double.

A: The argument to np.savetxt should be an array.
Add test = np.array(test) before saving the data.

*

*This will give an error if the data can not be converted to an array.

*You can print, for diagnosis, the shape of the array: print test.shape
Your output suggests that you have a float and then a list in your data, that are printed instead of the content of a NumPy array.


text:
Q: Do Python thread names reflect the number of open threads? If I see a stack trace like the following:
Exception in thread Thread-101:
Traceback (most recent call last):
  (...)

Does "Thread-101" necessarily mean that there are 101 active / open / performance-decreasing threads?  Or do those names work like IDs in a database, where the number always goes up, even if older records (threads) are deleted (closed)?

A: From the docs: https://docs.python.org/3/library/threading.html#threading.Thread.name

A string used for identification purposes only. It has no semantics.
  Multiple threads may be given the same name. The initial name is set by the constructor.

In addition, just to humor yourself, you can try this
>>> from threading import Thread
>>> t1 = Thread()
>>> t1
<Thread(Thread-1, initial)>
>>> t2 = Thread()
>>> t2
<Thread(Thread-2, initial)>
>>> t2.setName('Thread-1')
>>> t2
<Thread(Thread-1, initial)>
>>> t1
<Thread(Thread-1, initial)>
>>> t1.name
'Thread-1'
>>> t2.name
'Thread-1'

You can see that I have named both threads to the same name, so thread names being an index of any sort goes out the window.


text:
Q: In VBA Find a Cell on a Specified Excel Worksheet without Activating the Worksheet I am trying to locate a cell with formula "CAL JUMP INTENS" on a worksheet "this worksheet". The following code works.
worksheets("this worksheet").activate
Set target = Cells.Find(What:="CAL JUMP INTENS", After:=ActiveCell, _ LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)

However, I would not like to activate the worksheet "this worksheet". Is there a way to do this? I would need to locate this cell restricted to this worksheet "this worksheet" rather than the whole workbook.

A: Qualify the Find() method with a range and a sheet object:
Set target = Sheets("this worksheet").Cells.Find(What:="CAL JUMP INTENS", After:=ActiveCell, _ LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)

It's extremely rare in VBA that you ever have to Activate or Select anything.

A: Although SO provided an answer to your question, this serves just an additional info.
Do not pick it as answer. :)

*

*Use With Clause
With Worksheets("SheetName")
    .Cells.Find(What:="CAL JUMP INTENS", _
                After:=.Range("A1"), _ ' notice that this is referenced to your sheet
                LookIn:=xlFormulas, _
                LookAt:=xlWhole, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, _
                MatchCase:=True, _
                SearchFormat:=False)
End With

*Know the default values
If you know the default values of arguments and that is what you need, then might as well not be explicit about it. Above arguments you included are all default values (except, LookAt)so might as well omit them? When I say Default, it is the Excel settings when you start it anew (first time).
With Worksheets("SheetName")
    .Cells.Find(What:="CAL JUMP INTENS", _
                After:=.Range("A1"), _
                LookAt:=xlWhole)
End With

Or in your case, you really need not supply the After argument (since you are searching the entire worksheet). So,
Worksheets("SheetName").Cells.Find("CAL JUMP INTENS", , , xlWhole)

will work just fine.
Important:
As what SO noted, the default properties of find method for LookIn, LookAt and SearchOrder are the last used settings for it as what is pointed out in HERE.

"It is very important to understand that the settings LookIn, LookAt and SearchOrder are saved each time the Find Method is used. For this reason one should always specify these settings explicitly each and every time you use the Find Method. If you don't, you run the risk of using the Find Method with settings you were not aware of."


text:
Q: How to add a clear button in a popup window I am new to android development. I have created a popup window which is being called on a button click from the main activity class. I have some Edit text field on my pop window. can i clear all these edit text field on the pop up window through a button click? if yes then how? Thanks in advance!!
Below is what i am trying but it is giving null point exception.
 public void initatePopupWindow(View view)
{
    try
    {
        LayoutInflater inflater=(LayoutInflater)  ContactdetailsActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout=inflater.inflate(R.layout.popupwindow,(ViewGroup)findViewById(R.id.popuplayout));
        pw = new PopupWindow(layout, 500, 500, true);
        pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
        Button b1=(Button)layout.findViewById(R.id.cancel);
       b1.setOnClickListener(cancel_button_click_listener);
       Button b2=(Button)layout.findViewById(R.id.clear);

       b2.setOnClickListener(clear_fields);

    }
    catch (Exception e)
    {

    }
}
    private OnClickListener clear_fields= new OnClickListener()
    {
        public void onClick(View v)
        {

        ViewGroup group= (ViewGroup)findViewById(R.id.popuplayout);
            for(int i=0,count=getChildCount(); i<count; ++i)
            {
                View v1= group.getChildAt(i);
                if(v1 instanceof EditText)
                {
                    ((EditText)v1).setText("");
                }
                if(v1 instanceof ViewGroup && (((ViewGroup)v1).getChildCount() > 0))
                    onClick((ViewGroup)v1);
            }
        }
    };
    private OnClickListener cancel_button_click_listener=new OnClickListener()
    {
        public void onClick(View v)
        {
        pw.dismiss();
        }
    };

}

A: Are you getting your errors on this line?
ViewGroup group= (ViewGroup)findViewById(R.id.popuplayout);

ViewGroup group= (ViewGroup) layout.findViewById(R.id.popuplayout);//layout is your inflated

I think it might be beacuse you need to use the value you called on the layout inflator.
Anyway, I guess you should do instead: Get a reference of all your edit texts and then clear them one by one. Maybe keep an array of edit texts and walk through them and set their texts to "" instead of checking for the type.


text:
Q: Workaround LogbackValve Lack of Async Support I'm trying to create a Zipkin 1.31.1 server using Spring Boot 1.3.5.RELEASE to build a fat executable JAR with with Tomcat 8.0.33 embedded in it.  This is failing with the following error message:
java.lang.IllegalArgumentException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml. Also you must use a Servlet 3.0+ container

as described in Spring Boot Enable Async Supported Like in web.xml even with the suggested fix.
After setting breakpoints in the debugger, I found that the problem is the same as described in
How to Make LogbackValve async Supported
which wasn't answered and ultimately had the following improvement request created:
ch.qos.logback.access.tomcat.LogbackValve is not async-supported
Does anyone have any recommendations how I can workaround this issue?  I need help either:

*

*Replacing LogBackValve in the pipeline with a wrapper that supports async behavior

OR

*

*Disabling LogbackValve and/or removing it from the pipeline and living without its benefits

Any help you can provide would be much appreciated.  Thanks!

A: I figured out how to disable the bean that was injecting LogbackAccess.  This resolved the issue so that Zipkin is now accepting requests.


text:
Q: What non-integer number has the smallest factorial? Quick google search for factorial of non-integers led me to gamma function. I tried that in my calculator and it worked as expected for non-integers. Perhaps implements gamma function internally.
Now, for all positive numbers:
x < y => x! < y!

But not for numbers between 0 and 1. 0! = 1!. I played around to find this:
0!      1
0.1!    0.951
0.4!    0.887
0.425!  0.886
0.45!   0.885
0.5!    0.886
0.55!   0.888
0.6!    0.893
0.9!    0.96
1!      1

What is the floor for the gamma function (or the unrestricted by integers factorial function)? The floor is around 0.45 from the table. I'm curious to know what is the floor value and the number for which gamma is minimum.
Any significance or implications of these numbers would be interesting too.

A: As Martin R says, there is no known simple closed form for the minimum of the Gamma function. However, for fun, here are the first 1000 digits of the root (in Mathematica):
FindRoot[D[Gamma[x], x], {x, 1.5}, WorkingPrecision -> 1000]

which produces
1.46163214496836234126265954232572132846819620400644635129598840859878\
6440353801810243074992733725592750556793365533053341617365778466985829\
1771683816450246525426187920443843819783335597739619760747194319349371\
7541405945193010996372416652777217279167325088046396007693297814490147\
5185803414306536810631010706016949785457933765577116113646852653864407\
7372589890682262958196750529119944311972207258664056482074952272808066\
6492780264672546913947612363653574355170333094944302512419288581347767\
7638037268207228647702315131118425758160327915893181546219377794692453\
7619116776460200864228324583987363497206740454783034481431732283690209\
3646770017559017693843888399883958228679946842407928700859042045977138\
8194093679122118848402487784207298777528715900614407383331513574002791\
5353912845037515421736664287138645800903908013264994637024811461027624\
7799875927238664920666176370867887038347260422463147415264091765916362\
0499923428977096412741183720620861677533192913168549317959136215151559\
088748352371795155035